2014-01-23 21 views
3

我試圖創建一個文本字段,將能夠爲以下回應:的UITextField與「多」的代表

-(BOOL)textFieldShouldEndEditing:(UITextField *)textField 

要做到這一點,我有一個的UITextField子類,是其自身的委託:

[self setDelegate:self] 
  • 問題沒有。 1:在ios5設備上,只要點擊具有代表設置爲自我的文本字段,應用程序就會崩潰
  • 問題編號: 2:我仍然需要一些文本字段才能將委派通知發送給其他對象。

問題:在子類中實現委託方法的最簡單方法是什麼,但仍然允許外部對象成爲委託並接收相同的消息?

謝謝

+1

首先是什麼情景,你爲什麼什麼子類'UITextField'? – AMohan

回答

0

您可以使用Notifications。 讓它文本後場的通知,如下所示:

[[NSNotificationCenter defaultCenter] postNotificationName:@"custom notification name" object:self]; 

,並添加觀測到被認爲是外部委託類:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cacheUpdated:) name:@"custom notification name" object:nil]; 

這樣,文本後場的通知,這意味着它採取了一定的行動,並且您的外部委託類將被通知,因爲它已經在收聽那種通知。希望能幫助到你。

0

爲了創建你自己的委託,你需要定義新的協議到你的子類

@protocol MyUItestFieldDelegate <NSObject> 

- (void)customUITextFieldDelegateMethod; 

@end 

,您可以使用到您的控制器像

@interface MyViewController : UIViewController <MyUItestFieldDelegate> 
5

我有完全相同的問題(在Swift 3)。我解決了覆蓋delegate屬性的問題UITextField類。

在我的自定義視圖初始化,我掛鉤我自己的內部委託:

class CustomTextField: UITextField, UITextFieldDelegate { 

    override public init(frame: CGRect) { 
     super.init(frame: frame) 
     initCustomTextField() 
    } 

    required public init?(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
     initCustomTextField() 
    } 

    private func initCustomTextField() { 
     super.delegate = self // Note the super qualifier. 
    } 

    ... 

現在我們需要覆蓋上述delegate屬性:

private weak var userDelegate: UITextFieldDelegate? 

override var delegate: UITextFieldDelegate? { 
    get { return userDelegate } 
    set { userDelegate = newValue } 
} 

最後,每個UITextFieldDelegate協議方法您必須轉發調用外部代理,如果有的話:

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { 
    // Do your thing here, and then forward: 
    return self.delegate?.textFieldShouldBeginEditing?(self) ?? true 
} 

func textFieldDidBeginEditing(_ textField: UITextField) { 
    // Do your thing here, and then forward: 
    self.delegate?.textFieldDidEndEditing?(self) 
} 

... 

一個警告,如果你打算支持iOS的10還有:

func textFieldDidEndEditing(_ textField: UITextField) { 
    self.delegate?.textFieldDidEndEditing?(self) 
} 

/// This method will be called, instead of the above, on iOS ≥ 10. 
@available(iOS 10.0, *) 
func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) { 
    self.delegate?.textFieldDidEndEditing?(self, reason: reason) 
} 
+0

最佳答案。謝謝 ;) – Louis