目录
3 UITextView 和 UITextViewDelegate
4 UITextField 和 UITextFieldDelegate
1 UITextView & UITextField
1.1 UITextView
UITextView显示多行文本视图,接受编辑输入,类似于文本编辑器,获取焦点的时候会从底部弹出软键盘输入
1.2 UITextField
UITextField类似输入框,比如可用作search输入框,接受文本输入,获取焦点的时候会从底部弹出软键盘输入
如下图
2 Delegate
Delegate委托协议,有点类似于对接口类的实现,比如Android中Activity实现View.OnClickListener,当有Class实现了View.OnClickListener,那么就需要实现其接口方法onClick(View v),这里Delegate中也会存在相应的回调函数,比如UITextViewDelegate和UITextFieldDelegate各字都有自己可回调的函数。这是通过协议的方式给视图添加回调是IOS的特色。
2.1 UITextViewDelegate
UITextViewDelegate源码
@protocol UITextViewDelegate <NSObject, UIScrollViewDelegate>
@optional
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView;
- (BOOL)textViewShouldEndEditing:(UITextView *)textView;
- (void)textViewDidBeginEditing:(UITextView *)textView;
- (void)textViewDidEndEditing:(UITextView *)textView;
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
- (void)textViewDidChange:(UITextView *)textView;
- (void)textViewDidChangeSelection:(UITextView *)textView;
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction NS_AVAILABLE_IOS(10_0);
- (BOOL)textView:(UITextView *)textView shouldInteractWithTextAttachment:(NSTextAttachment *)textAttachment inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction NS_AVAILABLE_IOS(10_0);
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange NS_DEPRECATED_IOS(7_0, 10_0, "Use textView:shouldInteractWithURL:inRange:forInteractionType: instead");
- (BOOL)textView:(UITextView *)textView shouldInteractWithTextAttachment:(NSTextAttachment *)textAttachment inRange:(NSRange)characterRange NS_DEPRECATED_IOS(7_0, 10_0, "Use textView:shouldInteractWithTextAttachment:inRange:forInteractionType: instead");
@end
从上面源码中可以看到UITextViewDelegate中包含了
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
- (void)textViewDidChange:(UITextView *)textView;
- (void)textViewDidChangeSelection:(UITextView *)textView;
等一系列的回调函数,虽然没有给说明,但是函数名称却很清楚的表明了自己的作用。
2.2 UITextFieldDelegate
UITextFieldDelegate源码