把這幾個最基礎的控件屬性整理成一份可直接複製的速查碼,之後拉 UI 時就不必反覆翻文件。
關鍵是 insertSubview:atIndex: 的索引設為 0,讓它沉到最底層:
- (void)addImageView {
UIImage *pImage = [UIImage imageNamed:@"sea.png"];
self.pImageView = [[UIImageView alloc] initWithImage:pImage];
[self.view insertSubview:self.pImageView atIndex:0];
}
若想讓背景填滿整個畫面並隨尺寸伸縮,記得設定 contentMode 與 autoresizingMask。
- (void)addLabel {
UILabel *pLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 120, 50)];
pLabel.text = @"Hello World\nSecond Line";
pLabel.textAlignment = NSTextAlignmentCenter;
pLabel.textColor = [UIColor redColor];
pLabel.numberOfLines = 2; // 0 代表不限行數
pLabel.shadowColor = [UIColor blackColor];
pLabel.shadowOffset = CGSizeMake(2.0, 1.0);
pLabel.backgroundColor = [UIColor clearColor];
[self.view addSubview:pLabel];
[pLabel release];
}
numberOfLines 設為 0 才能完整顯示多行文字,設成固定數字會被截斷,這是最常見的踩坑點。
- (void)addTextField {
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 避免長文字被截;autocorrectionType 關掉鍵盤的自動更正(輸入帳號時很重要);secureTextEntry 則會把輸入內容變成圓點。
- (void)addButton {
UIButton *pBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[pBtn setFrame:CGRectMake(10, 70, 100, 40)];
[pBtn setTitle:@"Normal" forState:UIControlStateNormal];
[pBtn setTitle:@"HighLight" forState:UIControlStateHighlighted];
pBtn.showsTouchWhenHighlighted = YES;
[pBtn addTarget:self action:@selector(buttonDown:)
forControlEvents:UIControlEventTouchDown];
[pBtn addTarget:self action:@selector(buttonRelease:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:pBtn];
}
這裡示範了 UIButton 最有價值的能力:同一顆按鈕可以綁定多個事件。TouchDown 對應「按下瞬間」,TouchUpInside 對應「在按鈕內放開」,兩者搭配就能做出縮放、變色等觸覺回饋效果。