本文示範一個基礎範例:透過點擊按鈕,把文字輸入框(TextField)中的內容顯示到標籤(Label)上,並對輸入長度做簡單驗證。
首先在頭檔中建立文字框與標籤的 IBOutlet,並宣告按鈕的 IBAction:
#import <UIKit/UIKit.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
在 viewDidLoad 中設定 Label 的初始文字:
label.text = @"請輸入文字";
在 Click: 方法中取得輸入長度並進行判斷:若長度大於 30,則顯示 "Invalid Inputs" 並清空輸入框;否則格式化顯示輸入長度並清空:
-(IBAction)Click:(id)sender {
int textCount = textField.text.length;
if (textCount > 30) {
label.text = @"Invalid Inputs";
textField.text = NULL;
} else {
NSString *result = [NSString stringWithFormat:@"輸入長度為:%d", textCount];
label.text = result;
textField.text = NULL;
}
}
最後別忘了在 dealloc 中釋放 label 與 textField:
-(void)dealloc {
[label release];
[textField release];
[super dealloc];
}
透過這個範例,就能掌握 Button、TextField 與 Label 三者之間的基本互動。