首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS UITextField 通知機制:如何在統一處理方法中區分觸發文本框

     編輯:程式設計綜合問答

問題場景

註冊 `UITextFieldTextDidBeginEditingNotification`,多個文本框共用一個處理方法,如何知道是哪個 `textField` 觸發?

方案一:通過 notification.object 獲取(推薦)


// 註冊時 object 為 nil,表示接收所有文本框通知
[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(textFieldDidBegin:) 
                                             name:UITextFieldTextDidBeginEditingNotification 
                                           object:nil];

- (void)textFieldDidBegin:(NSNotification *)notification {
    UITextField *textField = notification.object;  // 關鍵:發送者就是文本框本身
    
    if (textField == self.textField1) {
        // 處理 textField1
    } else if (textField == self.textField2) {
        // 處理 textField2
    }
}

方案二:註冊時指定 object(精確過濾)


// 僅接收 textField1 的通知
[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(textField1DidBegin:) 
                                             name:UITextFieldTextDidBeginEditingNotification 
                                           object:self.textField1];

- (void)textField1DidBegin:(NSNotification *)notification {
    // 這裡確定是 textField1
    UITextField *tf = notification.object;
}

方案三:使用 Delegate 模式(Apple 推薦)


// 設置 delegate
self.textField1.delegate = self;
self.textField2.delegate = self;

// 實現 UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    // 直接獲得觸發的 textField,無需通知中心
    if (textField == self.textField1) { ... }
}

三種方案對比

方案優點缺點適用場景
Notification + object=nil鬆耦合、可跨層級傳遞需手動判斷、易忘記移除觀察者非直接關聯對象間通信
Notification + object=textField自動過濾、方法專一每個文本框需單獨註冊少量固定文本框
Delegate類型安全、編譯期檢查、生命周期自動管理強耦合、單播**文本框輸入控制首選**

最佳實踐建議

  1. 優先使用 Delegate:`textFieldDidBeginEditing:` 直接拿到 `textField`,最清晰
  2. 需跨層級/多對象監聽:用 Notification,從 `notification.object` 取發送者
  3. 必須移除觀察者:`deinit` / `viewWillDisappear` 中 `removeObserver:self`
  4. 避免在通知方法做耗時操作:主線程阻塞導致鍵盤彈出卡頓

Swift 版本


// NotificationCenter
NotificationCenter.default.addObserver(self, 
    selector: #selector(textFieldDidBegin(_:)), 
    name: UITextField.textDidBeginEditingNotification, 
    object: nil)

@objc func textFieldDidBegin(_ notification: Notification) {
    guard let textField = notification.object as? UITextField else { return }
    // 判斷 textField
}

// Delegate (推薦)
textField1.delegate = self
textField2.delegate = self

func textFieldDidBeginEditing(_ textField: UITextField) {
    // 直接判斷
}

總結

通知機制中 `notification.object` 就是發送通知的 `UITextField` 實例。但**文本框輸入控制首選 Delegate 模式**,更安全、更符合 Apple 設計規範。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved