2015-09-27 49 views
1

我正在構建自定義UIView,它需要輸入字段的初始化數組UITextFieldUITextView。我需要在輸入字段開始編輯時通知此自定義視圖而不設置代理當UITextField或UITextView開始編輯時收到通知

  1. UITextField我想出了一個想法,爲editing屬性添加觀察者。你有其他想法嗎?
  2. 我在UITextView找不到editing,我該怎麼辦。

的想法是,我需要這個自定義視圖作爲一個獨立的,並讓用戶自由設定,委託他們UIViewControllers

回答

-1

我想出了一個解決方案,我用UIKeyboardWillShowNotification收到通知時,鍵盤是關於顯示,然後遍歷我已經和領域檢查isFirstResponder()

NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillBeShown:", name: UIKeyboardWillShowNotification, object: nil) 

然後:

@objc private func keyboardWillBeShown(notification:NSNotification){ 

    for field in fields{ 

     if field.isFirstResponder(){ 

      // handle begin editing here 
     } 
    } 

} 
2

另一種方法是觀察UITextView的通知UITextViewTextDidBeginEditingNotificationUITextField的通知UITextFieldTextDidBeginEditingNotification

0

這裏有一個辦法,可以允許發送通知,這個自定義的UIView,而不需要將其設置爲代表:

import UIKit 


class SelfAwareTextField : UITextField, UITextFieldDelegate { 

// 
// Other delegate for this textfield 
// 
var otherDelegate: UITextFieldDelegate? = nil; 

// 
// Set weak reference to parent UIView 
// 
weak var parentView: UIView! 


// 
// Set the initializer 
// 
init(parentView pv: UIView, frame: CGRect) { 

    parentView = pv; 
    super.init(frame: frame); 

    // 
    // Do some custom initialization... 
    // 

    // Make this textfield a delegate to itself 
    self.delegate = self; 
} 

required init?(coder aDecoder: NSCoder) { 
    fatalError("init(coder:) has not been implemented") 
} 

func setDelegate(delegate _otherDelegate: UITextFieldDelegate){ 
    otherDelegate = _otherDelegate; 
} 



// 
// Write the textFieldDidBeginEditing method such that it 
// also calls the otherDelegate in the event it exists 
// and has this method defined 
// 
func textFieldDidBeginEditing(_ textField: UITextField){ 
    // 
    // Do stuff based on this textfield knowing it is starting to be used 
    // 
    // .... 
    // 


    // 
    // Do stuff for parent UIView 
    // ... 
    // (parentView as! CustomView).notified() // or something like this 
    // 


    // 
    // Do stuff for the other delegate 
    // 
    otherDelegate?.textFieldDidBeginEditing?(textField); 
} 


// Do similar thing as above for other methods in UITextFieldDelegate protocol 

} 

這個想法是,你讓這個文本字段是一個委託給它自己,所以它知道它的每個委託方法被調用。然後在每次調用這些委託方法時,可以使用自定義的UIView和任何其他與此文本字段關聯的委託進行操作。

相關問題