UITextViewDelegate拥有此
我正在编写自定义UITextView,但是在UITextView本身内部使用了委托,因此不能再在其他地方(例如,在UIViewController中)使用它。
因此,有一种方法可以检测用户何时在文本视图或文本字段中更改所选文本的范围,因为我需要插入符号的位置。我找不到任何NSNotification
做这样的事情:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(selectionDidChange:)
name: ?? // someNotification
object:textView];
然后使用选择器进行操作
-(void)selectionDidChange:(NSNotification *)notification {
//do something
}
我得到一个提示here,但不知道如何进行。
感谢您的帮助。谢谢。
我认为您必须为自定义TextField制定我们自己的协议。在自定义文本字段中,您将实现UItextfieldDelegate协议,并且您自己制作了防止UIVIewController的协议。
在您的.h中>
@protocol YourCustomTextFieldDelegate <NSObject> - (void) userDidChangeRange:(NSRange*) currentRange; @end @interface YourCustomTextField : UIView <UITextFieldDelegate> { UITextField *_customTextField; } @property(nonatomic, weak) id<YourCustomTextFieldDelegate> delegate
在您的.m中
中- (void)viewDidLoad{ [super viewDidLoad]; // Do any additional setup after loading the view. //Create your customTextField and add it to the view _customTextField.delegate = self; } #pragma mark - UItextField Delegate - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange: (NSRange)range replacementString:(NSString *)string { [self.delegate userDidChangeRange:range]; return YES; }
编辑:带有通知帖在您的.h
interface YourCustomTextField : UIView <UITextFieldDelegate> { UITextField *_customTextField; }
在您的.m中
- (void)viewDidLoad{ [super viewDidLoad]; // Do any additional setup after loading the view. //Create your customTextField and add it to the view _customTextField.delegate = self; } #pragma mark - UItextField Delegate - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange: (NSRange)range replacementString:(NSString *)string { [[[NSNotificationCenter defaultCenter] postNotificationName:@"YourNotificationName" object:self userInfo:@{@"range": range, @"textFieldTag" : @"[NSNumber numberWithInt:self.tag]}]; return YES; }
用户将通过]收听您的通知>
- (void) viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(rangeDiDChange) name:@"YourNotificationName" object:nil]; }
我建议在通知中将标签设置为识别文本字段,如果视图控制器中有很多自定义文本字段,则可以识别它。
希望它会有所帮助。
UITextViewDelegate拥有此
-(void)textViewDidChangeSelection:(UITextView *)textView {
//textView.selectedRange
}
重要的,关闭键盘(例如,如果您的工具栏带有完成按钮)将不会触发选择更改方法,即使选择现已更改(更改为0),所以我建议也在结束编辑方法中也调用此方法,同时还将所选范围手动设置为nil
-(void)textViewDidEndEditing:(UITextView *)textView {
textView.selectedRange = NSMakeRange(0, 0);
[self textViewDidChangeSelection:textView];
}
UITextViewDelegate拥有此