iOS被坑集錦
在做自己的***個(gè) iOS app,一路遇到不少困難,好在靠 Google 和 StackOverflow 都解決了,自己也不知道是否是 best practice。
隱藏 Tab bar
在以 Tab bar 劃分模塊的 app 中有些非一級(jí)界面是不需要底部的標(biāo)簽欄的,只需要在該 ViewController 的viewWillAppear:中加入設(shè)置標(biāo)簽欄隱藏的語(yǔ)句:
- - (void)viewWillAppear:(BOOL)animated {
- [super viewWillAppear:animated];
- self.tabBarController.tabBar.hidden = YES;
- }
但是,更好的作法是在 push 一個(gè) ViewController 之前,將其屬性hidesBottomBarWhenPushed設(shè)置為YES:
- SomeViewController *svc = [SomeViewController new];
- svc.hidesBottomBarWhenPushed = YES;
- [self.navigationController pushViewController:svc animated:YES];
計(jì)算 UIScrollView 的 ContentSize
有些 UIScrollView 的內(nèi)容是動(dòng)態(tài)增減的,這就需要重新計(jì)算 ContentSize,在改變內(nèi)容后增加以下代碼:
- -(void)resizeScrollViewContentSize {
- [self layoutIfNeeded];
- CGRect contentRect = CGRectZero;
- for (UIView *view in self.subviews) {
- contentRect = CGRectUnion(contentRect, view.frame);
- }
- self.contentSize = CGSizeMake(contentRect.size.width, contentRect.size.height);
- }
貌似必須要在計(jì)算前***執(zhí)行l(wèi)ayoutIfNeeded,否則有些 sub view 還沒有布局好。
計(jì)算多行文本的高度
UILabel 和 UITextView 可以顯示多行的文本,如果字符串是動(dòng)態(tài)獲取的話就需要計(jì)算整個(gè)文本的高度了(寬度一般是固定的),這時(shí)就要用到boundingRectWithSize: options: attributes: context:這個(gè) API 了(iOS7新增的)。為了方便自己工程中調(diào)用,我封裝了一下:
- + (CGRect)stringRect:(NSString *)string fontSize:(CGFloat)fontSize constraintWidth:(CGFloat)width constraintHeight:(CGFloat)height {
- UIFont *font = [UIFont systemFontOfSize:fontSize];
- CGSize constraint = CGSizeMake(width, height);
- NSDictionary *attributes = @{NSFontAttributeName : font};
- return [string boundingRectWithSize:constraint
- options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
- attributes:attributes
- context:nil];
- }
去掉字符串頭尾的空格
對(duì)于 UITextField 中輸入的字符串往往都要進(jìn)行 trim 處理,需要用到以下代碼:
- NSString *result = [self..nameTextField.text
- stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
監(jiān)聽 UITextView 的輸入,實(shí)時(shí)顯示字?jǐn)?shù)
首先要 conform(遵從?實(shí)現(xiàn)?) UITextViewDelegate,在textViewDidChange:中實(shí)現(xiàn)在 UILabel 中顯示當(dāng)前 UITextView 中的字?jǐn)?shù):
- - (void)textViewDidChange:(UITextView *)textView {
- _countLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)textView.text.length];
- [self setNeedsDisplay];
- }
設(shè)置 UITextView 的***輸入長(zhǎng)度
實(shí)現(xiàn)UITextViewDelegate中的textView:shouldChangeTextInRange:方法:
- -(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
- // if (range.location >= kMaxTextLength) { 這樣會(huì)導(dǎo)致移動(dòng)光標(biāo)后再輸入***長(zhǎng)度就失效
- if(textView.text.length >= kMaxTextLength) {
- return NO;
- }
- return YES;
- }