2013-03-03 176 views
2

有什麼辦法可以觀察對UITextField的selectedTextRange的更改嗎?UITextField - 觀察對selectedTextRange的更改嗎?

我試着觀察所有的UIControlEvents。但更改selectedTextRange不會觸發UIControlEvent。

另一個死衚衕 - UIKit類不符合KVO。

然後是UITextFieldTextDidChangeNotification。但這是對文本的更改。

任何想法?

回答

3

子類UITextField如下。

@interface WJTextField : UITextField 
@end 

@protocol WJTextFieldDelegate <UITextFieldDelegate> 
- (void) textFieldDidChangeSelection: (UITextField *) textField; 
@end 

實現:

@implementation WJTextField 

- (void) setSelectedTextRange: (UITextRange *) selectedTextRange 
{ 
    [super setSelectedTextRange: selectedTextRange]; 
    if ([self.delegate respondsToSelector: @selector(textFieldDidChangeSelection:)]) 
     [(id <WJTextFieldDelegate>) self.delegate textFieldDidChangeSelection: self]; 
} 

@end 

然後加入-textFieldDidChangeSelection:到文本字段的委託。

警告:此委託消息將只發送當光標移動時,它會打字或粘貼文本時,發送對於那些你必須實現textField:shouldChangeCharactersInRange:replacementString:,其中選擇範圍將事件或者設爲range.location + [string length](如果您返回YES)或保持不變(如果返回NO)。

+0

我只想提一提,在鍵入或粘貼文本時確實會觸發。至少在iOS8中,我沒有檢查其他東西。 – philipp 2015-02-10 09:59:29