- UITextField
示例代碼:
CGRect textFieldRect = CGRectMake(40, 70, 240, 30);
UITextField *textField = [[UITextField alloc] initWithFrame:textFieldRect];
// 常用屬性
textField.borderStyle = UITextBorderStyleRoundedRect; //設(shè)置邊框樣式
textField.placeholder = @"Hypnotize me"; //占位符
textField.returnKeyType = UIReturnKeyDone; //把換行符修改為 Done (默認為 return)
一些其他的常用屬性:
autocapitalizationType: 自動大寫功能 (包括 none, words, sentences, all characters)
autocorrectionType: 是否啟用拼寫建議
keyboardType: 設(shè)置彈出的鍵盤類型 (ASCII, E-mail Address, URL, Number Pad)
secureTextEntry: 是否啟用安全輸入 (即,是否用圓點替代輸入字符)
enablesReturnKeyAutomatically: 是否啟用換行鍵自動檢測
- UIResponder
UIResponder 是 UIKit 中的一個抽象類。UIResponder 定義了一系列方法,用于接收和處理用戶事件,例如觸摸事件、運動事件(如搖晃設(shè)備)和功能控制事件(如編輯文本或播放音樂)等。UIResponder 的子類會重寫這些方法,實現(xiàn)自己的事件響應(yīng)代碼。
第一響應(yīng)者設(shè)置,示例代碼:
[textField becomeFirstResponder]; // 成為 firstResponder
[textField resignFirstResponder]; //放棄 firstResponder
- 委托 (Delegation)
目標-動作(Target-Action)設(shè)計模式的工作方式:
當某個特定的事件發(fā)生時(例如按下按鈕),發(fā)生事件的一方會向指定的目標對象發(fā)送一個之前設(shè)定好的動作消息。簡單的例如UIButton的點擊事件。
對于復(fù)雜一些的,Apple 使用了委托的設(shè)計模式。
以 UITextField 為例,通過給 UITextField 對象設(shè)置委托,UITextField 對象會在發(fā)生事件時向委托發(fā)送相關(guān)消息,由委托處理該事件。
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 中的一種常見設(shè)計模式。
- 協(xié)議 (Protocols)
凡是支持委托的對象,其背后都有一個相應(yīng)的協(xié)議(等同 Java 或 C# 中的接口)。
對于 UITextField 的委托對象,相應(yīng)的協(xié)議示例代碼如下:
@protocol UITextFieldDelegate <NSObject>
@optional
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField;
- (void)textFieldDidBeginEditing:(UITextField *)textField;
// others ...
@end
尖括號里的 NSObject 是指 NSObject 協(xié)議,作用是聲明 UITextFieldDelegate 包含 NSObject 協(xié)議的全部方法。之后是聲明新協(xié)議特有的方法,最后使用 @end 指令結(jié)束。
協(xié)議所聲明的方法可以是必需的(默認)(required)或是可選的 (通常) (optional)。
注意:協(xié)議不是類,只是一組方法聲明。不能為協(xié)議創(chuàng)建對象,或者添加實例變量。協(xié)議自身不實現(xiàn)方法,需要由遵守協(xié)議的類來實現(xiàn)。
聲明某個類遵守協(xié)議的語法格式:在頭文件或類擴展的 @interface 指令末尾,將類所遵守的協(xié)議以逗號分隔的列表形式寫在尖括號里。
示例代碼:
@interface BNRHypnosisViewController () <UITextFieldDelegate>
@end
幾乎所有的委托都是弱引用屬性,原因:防止因強引用循環(huán)導(dǎo)致內(nèi)存泄漏。
@selector() 指令可以將選擇器(selector)轉(zhuǎn)換成數(shù)值,以便將其作為參數(shù)進行傳遞,示例代碼:
SEL clearSelector = @selector(textFieldShouldClear:);
if ([self.delegate respondsToSelector:clearSelector]) {
// do something ...
}
代碼地址:
https://github.com/Ranch2014/iOSProgramming4ed/tree/master/07-DelegationAndTextInput/HypnoNerd
《iOS編程(第4版)》 筆記