Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Objective-C Runtime 實戰(一):為 UITextField 加類目,鍵盤不再遮住輸入框

編輯:關於 Android 程式設計

Objective-C 的類目(Category)可以為既有類別補上方法,卻無法直接宣告實例變數與合成屬性。這時候就輪到 Runtime 的「關聯對象(Associated Object)」登場了。

本文以一個實用的例子演練:幫 UITextField 建立類目,讓它在被鍵盤遮住時自動把視圖往上推;順帶加上「點空白處收起鍵盤」的行為。使用方完全不需要額外寫程式碼。

效果與設計目標

  • 輸入框成為第一響應者時,監聽鍵盤彈出與收起的系統通知。
  • 計算輸入框底部與鍵盤頂部的距離,若會被遮住就上移對應高度。
  • 鍵盤收起後,視圖回到原位。
  • 點擊畫面空白處即可關閉鍵盤。

頭檔:用關聯屬性宣告類目屬性

// UITextField+CHTPositionChange.h
#import <UIKit/UIKit.h>

@interface UITextField (CHTHealper)

/** 是否支援視圖上移 */
@property (nonatomic, assign) BOOL canMove;
/** 點擊空白時要收起鍵盤、要移動的視圖,預設為當前控制器的 view */
@property (nonatomic, strong) UIView *moveView;
/** 輸入框底部與鍵盤頂部之間預留的距離 */
@property (nonatomic, assign) CGFloat heightToKeyboard;

@property (nonatomic, assign, readonly) CGFloat keyboardY;
@property (nonatomic, assign, readonly) CGFloat keyboardHeight;
@property (nonatomic, assign, readonly) CGFloat initialY;
@property (nonatomic, assign, readonly) CGFloat totalHeight;
@property (nonatomic, strong, readonly) UITapGestureRecognizer *tapGesture;
@property (nonatomic, assign, readonly) BOOL hasContentOffset;

@end

實作:關聯對象是類目屬性的地基

先定義全域唯一鍵作為關聯識別碼,再用 @dynamic 告訴編譯器 setter/getter 由我們手動實作。

static char canMoveKey;
static char moveViewKey;

@implementation UITextField (CHTHealper)

@dynamic canMove;
@dynamic moveView;

讀寫方法就是一對 objc_setAssociatedObject 與 objc_getAssociatedObject:

- (void)setCanMove:(BOOL)canMove {
    // 參數依序為:關聯對象、關聯鍵、關聯值、關聯策略
    objc_setAssociatedObject(self, &canMoveKey, @(canMove), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)canMove {
    // 關聯值存的是物件,取出後需轉型
    return [objc_getAssociatedObject(self, &canMoveKey) boolValue];
}

要判斷「是否被遮住」,先取得輸入框在視窗中的座標

// 取得 TextField 左上角在當前 window 中的座標
[self convertPoint:self.bounds.origin toView:[UIApplication sharedApplication].keyWindow]

接著還需要知道鍵盤高度,這只能透過系統通知取得。問題是「何時註冊、何時移除」?最自然的時機是成為/放棄第一響應者的那一刻。

但如果直接覆寫 becomeFirstResponder,就會蓋掉 UITextField 自身的實作,最明顯的後果是「光標消失」。這裡要用到 Runtime 的另一項能力:方法交換(Method Swizzling)。

方法交換:用 dispatch_once 保證只換一次

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        SEL systemSel  = @selector(initWithFrame:);
        SEL mySel      = @selector(setupInitWithFrame:);
        [self exchangeSystemSel:systemSel bySel:mySel];

        SEL systemSel2 = @selector(becomeFirstResponder);
        SEL mySel2     = @selector(newBecomeFirstResponder);
        [self exchangeSystemSel:systemSel2 bySel:mySel2];

        SEL systemSel3 = @selector(resignFirstResponder);
        SEL mySel3     = @selector(newResignFirstResponder);
        [self exchangeSystemSel:systemSel3 bySel:mySel3];

        SEL systemSel4 = @selector(initWithCoder:);
        SEL mySel4     = @selector(setupInitWithCoder:);
        [self exchangeSystemSel:systemSel4 bySel:mySel4];
    });
    [super load];
}

// 交換步驟
+ (void)exchangeSystemSel:(SEL)systemSel bySel:(SEL)mySel {
    Method systemMethod = class_getInstanceMethod([self class], systemSel);
    Method myMethod     = class_getInstanceMethod([self class], mySel);

    // 先嘗試動態添加方法:實作內容是「被交換的方法」
    BOOL isAdd = class_addMethod(self, systemSel,
            method_getImplementation(myMethod), method_getTypeEncoding(myMethod));
    if (isAdd) {
        // 添加成功代表類中原本沒有這個實作,把系統方法換到這個新位置
        class_replaceMethod(self, mySel,
                method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));
    } else {
        // 否則直接交換兩個方法的實作
        method_exchangeImplementations(systemMethod, myMethod);
    }
}

這裡刻意交換了兩組 init 方法(initWithFrame: 與 initWithCoder:),才能同時涵蓋「用程式碼建立」與「用 xib/storyboard 拖出來」的輸入框。

- (instancetype)setupInitWithCoder:(NSCoder *)aDecoder {
    [self setup];
    return [self setupInitWithCoder:aDecoder];
}

- (instancetype)setupInitWithFrame:(CGRect)frame {
    [self setup];
    return [self setupInitWithFrame:frame];
}

- (void)setup {
    self.heightToKeyboard = 10;
    self.canMove = YES;
    self.keyboardY = 0;
    self.totalHeight = 0;
    self.tapGesture = [[UITapGestureRecognizer alloc]
            initWithTarget:self action:@selector(tapAction)];
}

第一響應者的進入與離開

成為第一響應者時註冊鍵盤通知並掛上點擊手勢;放棄時移除通知與手勢。這裡的 newBecomeFirstResponder 在交換之後,實際上指向原本的系統實作。

- (BOOL)newBecomeFirstResponder {
    // 未指定 moveView 時,預設為當前控制器的 view
    if (self.moveView == nil) {
        self.moveView = [self viewController].view;
    }
    // 避免重複掛上同一個手勢
    if (![self.moveView.gestureRecognizers containsObject:self.tapGesture]) {
        [self moveView].addGestureRecognizer:self.tapGesture;
    }
    // 重複點擊同一個輸入框,或設定為不可移動時,不再重複註冊
    if ([self isFirstResponder] || !self.canMove) {
        return [self newBecomeFirstResponder];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self
            selector:@selector(showAction:)
            name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
            selector:@selector(hideAction:)
            name:UIKeyboardWillHideNotification object:nil];
    return [self newBecomeFirstResponder];
}

- (BOOL)newResignFirstResponder {
    if ([self.moveView.gestureRecognizers containsObject:self.tapGesture]) {
        [self.moveView removeGestureRecognizer:self.tapGesture];
    }
    if (!self.canMove) {
        return [self newResignFirstResponder];
    }
    BOOL result = [self newResignFirstResponder];
    [[NSNotificationCenter defaultCenter] removeObserver:self
            name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
            name:UIKeyboardWillHideNotification object:nil];
    // 如果是切換到另一個輸入框,鍵盤不會收起,這裡手動復位
    [self hideKeyBoard:0];
    return result;
}

// 取得當前 TextField 所屬的 controller
- (UIViewController *)viewController {
    UIView *next = self;
    while (1) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
        if (next.superview == nil) { break; }
        next = next.superview;
    }
    return nil;
}

鍵盤彈出:計算並執行位移

- (void)showAction:(NSNotification *)sender {
    if (!self.canMove) { return; }
    self.keyboardY = [sender.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;
    self.keyboardHeight = [sender.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    [self keyboardDidShow];
}

- (void)hideAction:(NSNotification *)sender {
    if (!self.canMove || self.keyboardY == 0) { return; }
    [self hideKeyBoard:0.25];
}

- (void)keyboardDidShow {
    if (self.keyboardHeight == 0) { return; }
    // 輸入框在 window 中的 Y 座標
    CGFloat fieldYInWindow = [self convertPoint:self.bounds.origin
                                         toView:[UIApplication sharedApplication].keyWindow].y;
    // 判斷是否需要上移,以及要移多少
    CGFloat height = (fieldYInWindow + self.heightToKeyboard + self.frame.size.height) - self.keyboardY;
    CGFloat moveHeight = height > 0 ? height : 0;

    [UIView animateWithDuration:0.25 animations:^{
        if (self.hasContentOffset) {
            // 若 moveView 是 ScrollView,改動 contentOffset
            UIScrollView *scrollView = (UIScrollView *)self.moveView;
            scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x,
                    scrollView.contentOffset.y + moveHeight);
        } else {
            CGRect rect = self.moveView.frame;
            self.initialY = rect.origin.y;
            rect.origin.y -= moveHeight;
            self.moveView.frame = rect;
        }
        self.totalHeight += moveHeight; // 記錄位移量以便復位
    }];
}

- (void)hideKeyBoard:(CGFloat)duration {
    [UIView animateWithDuration:duration animations:^{
        if (self.hasContentOffset) {
            UIScrollView *scrollView = (UIScrollView *)self.moveView;
            scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x,
                    scrollView.contentOffset.y - self.totalHeight);
        } else {
            CGRect rect = self.moveView.frame;
            rect.origin.y += self.totalHeight;
            self.moveView.frame = rect;
        }
        self.totalHeight = 0;
    }];
}

// 點擊空白處收起鍵盤
- (void)tapAction {
    [[self viewController].view endEditing:YES];
}

小結

這個例子示範了 Runtime 最常被使用的兩項技巧:以關聯對象替類目「補上屬性」,以及以方法交換在不破壞原實作的前提下插入自己的行為。兩者搭配,就能把原本需要每個頁面重複書寫的鍵盤處理邏輯,收斂成一個引入即用的類目。

提醒一句:方法交換會改變全域行為,實作時務必用 dispatch_once 保證只交換一次,並在交換後的方法內部呼叫「交換後的自己」,否則很容易造成無限遞迴。新專案若使用 Swift,這類需求也可以評估 Combine/ delegate 或自訂 InputAccessoryView 等更直觀的做法。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved