- (void)addButton:(id)sender {
UIButton *pBtton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[pBtton setFrame:CGRectMake(10, 70, 100, 40)];
[pBtton setTitle:@"Normal" forState:UIControlStateNormal];
pBtton.showsTouchWhenHighlighted = YES; // 點擊時閃亮
[pBtton addTarget:self
action:@selector(buttonDown:)
forControlEvents:UIControlEventTouchDown];
[self.view addSubview:pBtton];
}
注意 buttonWithType: 回傳的是系統持有的物件,不需要也不應該 release;另外 setTitle:forState: 必須指定狀態,最常用的是 UIControlStateNormal,若也要設定點擊後的樣子,就再對 UIControlStateHighlighted 設一次。
- (void)addLabel:(id)sender {
UILabel *pLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 120, 50)];
pLabel.text = @"HelloWorld\nSecondLine";
pLabel.font = [UIFont fontWithName:@"Verdana" size:18];
pLabel.textAlignment = NSTextAlignmentCenter;
pLabel.textColor = [UIColor redColor];
pLabel.numberOfLines = 2; // 顯示行數
pLabel.shadowColor = [UIColor blackColor];
pLabel.shadowOffset = CGSizeMake(2.0, 1.0);
pLabel.backgroundColor = [UIColor clearColor];
[self.view addSubview:pLabel];
[pLabel release];
}
numberOfLines 設為 0 代表不限制行數,這是多行文字時的首選;文字超出寬度時,還需搭配 lineBreakMode 才能正確截斷。
- (void)addTextField:(id)sender {
UITextField *pTextField = [[UITextField alloc] initWithFrame:CGRectMake(10, 116, 200, 31)];
pTextField.borderStyle = UITextBorderStyleRoundedRect;
pTextField.font = [UIFont systemFontOfSize:18.0];
pTextField.adjustsFontSizeToFitWidth = YES; // 依寬度縮放字體
pTextField.minimumFontSize = 2.0;
pTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
pTextField.keyboardType = UIKeyboardTypeDefault;
pTextField.autocorrectionType = UITextAutocorrectionTypeNo;
pTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
pTextField.returnKeyType = UIReturnKeyDone;
pTextField.secureTextEntry = YES; // 密碼顯示為星號
pTextField.delegate = self;
[self.view addSubview:pTextField];
[pTextField release];
}
adjustsFontSizeToFitWidth 必須與 minimumFontSize 搭配使用,否則系統不知道最小能縮到多少。
遵循 UITextFieldDelegate 協議,實作 textFieldShouldReturn: 即可在按下 Done 時讓出焦點:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder]; // 放棄第一響應者身分
return YES;
}
UITextField 沒有 maxLength 屬性,必須在 shouldChangeCharactersInRange: 中自行判斷。做法是「先套上本次變更,再看長度」:
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
int MAX_LENGTH = 10;
NSMutableString *pNewString = [NSMutableString stringWithString:textField.text];
[pNewString replaceCharactersInRange:range withString:string];
return ([pNewString length] <= MAX_LENGTH);
}
回傳 NO 代表拒絕這次輸入,螢幕上的文字就不會改變。這個方法也常用來過濾字元,例如只允許數字:檢查 string 是否為空白字串(刪除操作),再逐一驗證每個字元是否落在 0–9 範圍內即可。