Button、TextField、Label 三者連線,是 iOS 最基礎的互動範式:使用者輸入、點擊、畫面回應。這篇做一個小練習,順便把輸入長度的判斷一起處理。
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
@interface ViewController : UIViewController
{
// 建立文字輸入框
IBOutlet UITextField *textField;
// 建立標籤顯示文字
IBOutlet UILabel *label;
}
@property (nonatomic, retain) UITextField *textField;
@property (nonatomic, retain) UILabel *label;
- (IBAction)Click:(id)sender;
@end
#import "ViewController.h"
@implementation ViewController
@synthesize textField, label;
- (void)viewDidLoad {
[super viewDidLoad];
// 把從 storyboard 讀入的 Label 文字換成本程式的初始提示
label.text = @"請輸入文字";
}
- (IBAction)Click:(id)sender {
int textCount = textField.text.length;
if (textCount > 30) {
// 超過上限
label.text = @"Invalid Inputs";
textField.text = nil;
} else {
// 正常範圍
NSString *result = [NSString stringWithFormat:@"輸入長度為:%d", textCount];
label.text = result;
textField.text = nil;
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)dealloc {
[label release];
[textField release];
[super dealloc];
}
@end
清空輸入框請用 nil 而非 NULL。 兩者在編譯層面等價,但 nil 是 Objective-C 對物件空值的慣用寫法,語意清楚。
先按連線,再按執行。 若忘了在 Interface Builder 裡把 button 的 Touch Up Inside 連到 Click:,程式不會報錯,只是按下去沒反應,這是新手最常困惑的一點。
注意 nil 訊息行為。 如果 textField 尚未連線就是 nil,textField.text.length 會得到 0 而不會崩潰——Objective-C 允許對 nil 發送訊息。這既方便也隱藏問題,所以畫面行為不如預期時,第一件事是檢查連線。
別忘了 delegate。 想讓按鍵盤 Return 時收起鍵盤或觸發送出,需要設定 text field 的 delegate 並實作 textFieldShouldReturn:。
另外,範例中的 viewDidUnload 在後續 iOS 版本已不再被呼叫,MRC 時代用它釋放 outlet 的寫法在新專案中不必沿用;ARC 之下 dealloc 裡也不需要手動 release。