委托与文本输入

  • UITextField

示例代码:

CGRect textFieldRect = CGRectMake(40, 70, 240, 30);
UITextField *textField = [[UITextField alloc] initWithFrame:textFieldRect];

// 常用属性
textField.borderStyle = UITextBorderStyleRoundedRect; //设置边框样式
textField.placeholder = @"Hypnotize me"; //占位符
textField.returnKeyType = UIReturnKeyDone; //把换行符修改为 Done (默认为 return)

一些其他的常用属性:

autocapitalizationType:  自动大写功能 (包括 none, words, sentences, all characters)
autocorrectionType:  是否启用拼写建议
keyboardType:  设置弹出的键盘类型 (ASCII, E-mail Address, URL, Number Pad)
secureTextEntry:  是否启用安全输入 (即,是否用圆点替代输入字符)
enablesReturnKeyAutomatically:  是否启用换行键自动检测
  • UIResponder

UIResponderUIKit 中的一个抽象类。UIResponder 定义了一系列方法,用于接收和处理用户事件,例如触摸事件、运动事件(如摇晃设备)和功能控制事件(如编辑文本或播放音乐)等。UIResponder 的子类会重写这些方法,实现自己的事件响应代码。

第一响应者设置,示例代码:

[textField becomeFirstResponder]; // 成为 firstResponder

[textField resignFirstResponder]; //放弃 firstResponder
  • 委托 (Delegation)

目标-动作(Target-Action)设计模式的工作方式:
当某个特定的事件发生时(例如按下按钮),发生事件的一方会向指定的目标对象发送一个之前设定好的动作消息。简单的例如 UIButton 的点击事件。

对于复杂一些的,Apple 使用了委托的设计模式。
UITextField 为例,通过给 UITextField 对象设置委托,UITextField 对象会在发生事件时向委托发送相关消息,由委托处理该事件。

UITextField 的常用委托方法如下:

- (void)textFieldDidBeginEditing:(UITextField *)textField;  // became first responder
- (void)textFieldDidEndEditing:(UITextField *)textField;

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField;  // return NO to disallow editing
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField;
- (BOOL)textFieldShouldClear:(UITextField *)textField;
- (BOOL)textFieldShouldReturn:(UITextField *)textField;

委托(delegation)是 Cocoa Touch 中的一种常见设计模式。

  • 协议 (Protocols)

凡是支持委托的对象,其背后都有一个相应的协议(等同 Java 或 C# 中的接口)。

对于 UITextField 的委托对象,相应的协议示例代码如下:

@protocol UITextFieldDelegate 

@optional

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField;        
- (void)textFieldDidBeginEditing:(UITextField *)textField;  

 // others ...

@end

尖括号里的 NSObject 是指 NSObject 协议,作用是声明 UITextFieldDelegate 包含 NSObject 协议的全部方法。之后是声明新协议特有的方法,最后使用 @end 指令结束。

协议所声明的方法可以是必需的(默认)(required)或是可选的 (通常) (optional)。

注意:协议不是类,只是一组方法声明。不能为协议创建对象,或者添加实例变量。协议自身不实现方法,需要由遵守协议的类来实现。

声明某个类遵守协议的语法格式:在头文件或类扩展的 @interface 指令末尾,将类所遵守的协议以逗号分隔的列表形式写在尖括号里。
示例代码:

@interface BNRHypnosisViewController () 
@end

几乎所有的委托都是弱引用属性,原因:防止因强引用循环导致内存泄漏。

@selector() 指令可以将选择器(selector)转换成数值,以便将其作为参数进行传递,示例代码:

SEL clearSelector = @selector(textFieldShouldClear:);

if ([self.delegate respondsToSelector:clearSelector]) {
    // do something ...
}

代码地址:
https://github.com/Ranch2014/iOSProgramming4ed/tree/master/07-DelegationAndTextInput/HypnoNerd

《iOS编程(第4版)》 笔记

你可能感兴趣的:(委托与文本输入)