当前位置: 首页 > 科技观察

iOS被坑的亮点

时间:2023-03-12 12:04:52 科技观察

我在做我的第一个iOS应用,一路上遇到了很多困难。幸好Google和StackOverflow已经解决了,不知道是不是最佳实践。隐藏Tabbar应用中一些被Tabbar划分为模块的非一级界面不需要底部tabbar。只需要在ViewController的viewWillAppear:中添加设置标签栏隐藏的语句:-(void)viewWillAppear:(BOOL)animated{[superviewWillAppear:animated];self.tabBarController.tabBar.hidden=YES;}然而,最好在推送ViewController之前将其属性hidesBottomBarWhenPushed设置为YES:SomeViewController*svc=[SomeViewControllernew];svc.hidesBottomBarWhenPushed=YES;[self.navigationControllerpushViewController:svcanimated:YES];计算UIScrollView的ContentSize有些UIScrollView的内容是动态增加或减少的,需要重新计算ContentSize,改变内容后,添加如下代码:subviews){contentRect=CGRectUnion(contentRect,view.frame);}self.contentSize=CGSizeMake(contentRect.size.width,contentRect.size.height);}看来必须先执行layoutIfNeeded再计算,否则有些子视图还没有布置好。计算多行文字的高度UILabel和UITextView可以显示多行文字。如果是动态获取字符串,则需要计算整个文本的高度(宽度一般是固定的)。本例中使用了boundingRectWithSize:options:attributes:context:这个API已经添加(iOS7新添加)。为了方便在自己的项目中调用,我封装了:+(CGRect)stringRect:(NSString*)stringfontSize:(CGFloat)fontSizeconstraintWidth:(CGFloat)widthconstraintHeight:(CGFloat)height{UIFont*font=[UIFontsystemFontOfSize:fontSize];CGSizeconstraint=CGSizeMake(width,height);NSDictionary*attributes=@{NSFontAttributeName:font};return[stringboundingRectWithSize:constraintoptions:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeadingattributes:attributescontext:nil];}删除UITextField字符串开头和结尾的空格要进行修剪处理,需要使用如下代码:NSString*result=[self..nameTextField.textstringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceCharacterSet]];监听UITextView的输入,实时显示字数。首先,conform(comply?Implement?)UITextViewDelegate,在textViewDidChange中:在UILabel中显示当前UITextView中的字符数:-(void)textViewDidChange:(UITextView*)textView{_countLabel.text=[NSStringstringWithFormat:@"%lu",(unsignedlong)textView.text.length];[selfsetNeedsDisplay];}设置UITextView最大输入长度实现UITextViewDelegate中的textView:shouldChangeTextInRange:Method:-(BOOL)textView:(UITextView*)textViewshouldChangeTextInRange:(NSRange)rangereplacementText:(NSString*)text{//if(range.location>=kMaxTextLength){这会导致光标在输入前移动***长度无效if(textView.text.length>=kMaxTextLength){returnNO;}returnYES;}