您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 開發實戰易错點整理:24 個高頻坑位與對應解法

編輯:iOS 開發綜合

日常開發中反覆遇到的細碎問題,往往比架構設計更耗時間。以下整理一批高頻踩坑點與可直接複用的程式碼片段。

1. 點擊 return 收起鍵盤

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [_contactTextFiled resignFirstResponder];
    return YES;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        [_contactTextFiled becomeFirstResponder];
    }
    return YES;
}

2. 一行程式碼移除所有子視圖

關鍵是 makeObjectsPerformSelector:,這個方法在很多場景下都能用來簡化程式碼。

[xxxView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

3. 解決刷新單個 cell 或 section 時閃一下

做法是暫時關閉動畫,包在 begin/end updates 之間:

[UIView setAnimationsEnabled:NO];
[_listTable beginUpdates];
[_listTable reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section]
         withRowAnimation:UITableViewRowAnimationNone];
[_listTable endUpdates];
[UIView setAnimationsEnabled:YES];

4. 用 mask 畫出弧形頂部的視圖

思路是用 UIBezierPath 描述曲線,再把它的 CGPath 設為 layer 的 mask:

UIView *myCustomView = [[UIView alloc] initWithFrame:CGRectMake(0, 204, kScreenWidth, 120)];
myCustomView.backgroundColor = [UIColor whiteColor];
[view addSubview:myCustomView];

UIBezierPath *bezierPath = [UIBezierPath bezierPath];
[bezierPath moveToPoint:CGPointMake(0, 0)];
[bezierPath addCurveToPoint:CGPointMake(myCustomView.width, 0)
              controlPoint1:CGPointMake(0, 0)
              controlPoint2:CGPointMake(myCustomView.width / 2, 40)];
[bezierPath addLineToPoint:CGPointMake(myCustomView.width, myCustomView.height)];
[bezierPath addLineToPoint:CGPointMake(0, myCustomView.height)];
[bezierPath closePath];

CAShapeLayer *shapLayer = [CAShapeLayer layer];
shapLayer.path = bezierPath.CGPath;
myCustomView.layer.mask = shapLayer;
myCustomView.layer.masksToBounds = YES;

5. UISearchController 導致搜索框重疊

在 UITableView 中使用 UISearchController 時,若搜索框已處於激活狀態又推入了新的 VC,會出現搜索框重疊。解法是設定 definesPresentationContext 這個布林值。

6. TabBar 的隱藏與顯示

直接調整 UITabBar 與其容器視圖的 frame,並包在動畫區塊中:

- (void)hidesTabBar:(BOOL)hidden {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0];
    for (UIView *view in self.tabBarController.view.subviews) {
        if ([view isKindOfClass:[UITabBar class]]) {
            if (hidden) {
                [view setFrame:CGRectMake(view.frame.origin.x,
                                          [UIScreen mainScreen].bounds.size.height,
                                          view.frame.size.width,
                                          view.frame.size.height)];
            } else {
                [view setFrame:CGRectMake(view.frame.origin.x,
                                          [UIScreen mainScreen].bounds.size.height - 49,
                                          view.frame.size.width,
                                          view.frame.size.height)];
            }
        } else if ([view isKindOfClass:NSClassFromString(@"UITransitionView")]) {
            if (hidden) {
                [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y,
                                          view.frame.size.width,
                                          [UIScreen mainScreen].bounds.size.height)];
            } else {
                [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y,
                                          view.frame.size.width,
                                          [UIScreen mainScreen].bounds.size.height - 49)];
            }
        }
    }
    [UIView commitAnimations];
}

7. 取得 cell 上按鈕所屬的 section 與 row

UIView *view = [sender superview];
GCCollectGroupCellTableViewCell *cell = (GCCollectGroupCellTableViewCell *)[view superview];
NSIndexPath *indexPath = [_listTable indexPathForCell:cell];
NSLog(@"%@", detailArr[indexPath.section - 1][indexPath.row][@"comname"]);

8. NSAttributedString 與 NSString 互轉

NSAttributedString *attrStr = [[NSAttributedString alloc]
    initWithData:[_CompanyFileds.comname dataUsingEncoding:NSUnicodeStringEncoding]
         options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}
documentAttributes:nil error:nil];
_CompanyFileds.comname = attrStr.string;

9. 監聽 UITextField 內容變化

// 註冊監聽
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(changeForKeyWord:)
                                             name:UITextFieldTextDidChangeNotification
                                           object:nil];

// 監聽 _pageTextField.text 的變化
- (void)changeForKeyWord:(NSNotification *)sender {
    [self checkNum:_pageTextField.text];
}

- (BOOL)checkNum:(NSString *)str {
    NSString *regex = @"^[0-9]+(\\.[0-9]{2})?$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:str];
    if (!isMatch && _pageTextField.text.length > 0) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil
                                                          message:@"頁碼只能輸入數字哦"
                                                         delegate:self
                                                cancelButtonTitle:@"重新輸入"
                                                otherButtonTitles:nil];
        alertView.delegate = self;
        [alertView show];
        return NO;
    }
    return YES;
}

10. 監聽 UITextField 的開始編輯事件

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(enterEdited:)
                                             name:UITextFieldTextDidBeginEditingNotification
                                           object:nil];

- (void)enterEdited:(NSNotification *)sender {
    // 事件邏輯寫在這裡
}

11. 解決手勢衝突:父視圖手勢影響子視圖

方法一:實作 UIGestureRecognizerDelegate,對特定類型的子視圖直接放行。

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
       shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view isKindOfClass:[UIButton class]] ||
        [touch.view isKindOfClass:[UITableViewCell class]] ||
        [touch.view isKindOfClass:[UITextField class]] ||
        [touch.view isKindOfClass:[UITextView class]]) {
        return NO;
    }
    return YES;
}

方法二:利用 UIView 的 exclusiveTouch 屬性。設定 [self setExclusiveTouch:YES]; 可以讓同一界面上多個控件在接收事件時具備排他性,藉此避免衝突。

12. UITextField 邊框樣式與內容內距

// 1. 記得先在 IB 中把邊框樣式選為「無」,否則程式碼設定無效
_textBoxName.layer.borderWidth = 1.0f;
_textBoxName.layer.borderColor = [UIColor colorWithRed:0xbf/255.0f
                                                 green:0xbf/255.0f
                                                  blue:0xbf/255.0f
                                                 alpha:1].CGColor;

// 2. 調整文字距離左側邊框的距離
_textBoxName.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 16, 51)];
_textBoxName.leftViewMode = UITextFieldViewModeAlways;

13. 圖片旋轉動畫

#pragma mark - 更新按鈕動畫
- (void)rotate360DegreeWithImageViews:(UIImageView *)myViews {
    CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI * 2.0];
    rotationAnimation.duration = 1.0;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = 100000;
    [myViews.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}

// 停止動畫
[myViews.layer removeAllAnimations];

14. 改變 cell 的選中背景色

cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
cell.selectedBackgroundView.backgroundColor = COLOR_BACKGROUNDVIEW;

// 若不需要任何選中效果
cell.selectionStyle = UITableViewCellSelectionStyleNone;

15. 浮點數取整的四種方式

Objective-C 擴充自 C,很多用法與 C 一致。浮點數轉整數有四種常見做法:

// 1. 直接強制轉型,直接丟棄小數部分
float f = 1.5;
int a = (int)f;            // 結果為 1

// 2. floor(),向下取整
float f = 1.6;
int a = floor(f);          // 結果為 1
// 取得不大於該浮點數的最大整數。正數等同捨棄小數部分;
// 負數則是捨棄小數部分後再減 1

// 3. ceil(),向上取整
float f = 1.5;
int a = ceil(f);           // 結果為 2
// 取得不小於該浮點數的最小整數。正數等同捨棄小數部分後加 1;
// 負數則等同捨棄小數部分

// 4. 加 0.5 後強制轉型,模擬四捨五入
float f = 1.5;
int a = (int)(f + 0.5);    // 結果為 2

這些片段看起來零散,但累積起來能省下大量查文件與除錯的時間。遇到類似症狀時,回頭翻一翻往往比重新摸索快得多。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved