這篇文章把常用 UIKit 控件的創建代碼集中整理在一起,作為開發時的速查參考。每個控件都給出了初始化、屬性配置與事件綁定的完整示例。
// 載入圖片 UIImage *pImage = [UIImage imageNamed:@"sea.png"]; // 用圖片直接初始化 self.pImageView = [[UIImageView alloc] initWithImage:pImage]; // 插入到父視圖最底層 [self.view insertSubview:self.pImageView atIndex:0];
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; // 0 表示不限行數 pLabel.shadowColor = [UIColor blackColor]; pLabel.shadowOffset = CGSizeMake(2.0, 1.0); pLabel.backgroundColor = [UIColor clearColor]; [self.view addSubview:pLabel];
若希望文本超出時自動縮小字號,可加上 pLabel.adjustsFontSizeToFitWidth = YES; 並配合 minimumScaleFactor。
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];
UITextFieldDelegate 常用方法:
// 點擊回車鍵收鍵盤
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
// 點擊背景收鍵盤
- (IBAction)backgroundTap:(id)sender {
[_numberField resignFirstResponder];
[_codeField resignFirstResponder];
}
// 通過 touchesBegan 收鍵盤
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.view endEditing:YES];
}
// 限制輸入長度
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
NSUInteger maxLength = 10;
NSMutableString *newString = [NSMutableString stringWithString:textField.text];
[newString replaceCharactersInRange:range withString:string];
return ([newString length] <= maxLength);
}
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];
[self.view addSubview:pBtn];
- (void)buttonDown:(id)sender {
// 響應邏輯
}
UIButton *pCheckboxButton = [UIButton buttonWithType:UIButtonTypeCustom];
[pCheckboxButton setFrame:CGRectMake(10, 155, 36, 36)];
[pCheckboxButton setImage:[UIImage imageNamed:@"checkbox_off.png"]
forState:UIControlStateNormal];
[pCheckboxButton setImage:[UIImage imageNamed:@"checkbox_on.png"]
forState:UIControlStateSelected];
[pCheckboxButton addTarget:self action:@selector(checkboxClick:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:pCheckboxButton];
- (void)checkboxClick:(UIButton *)btn {
btn.selected = !btn.selected;
}
UISlider *pSlider = [[UISlider alloc] initWithFrame:CGRectMake(10, 195, 300, 20)];
pSlider.minimumValue = 0;
pSlider.maximumValue = 100;
pSlider.continuous = YES; // 滑動過程持續觸發
pSlider.value = 50;
pSlider.minimumValueImage = [UIImage imageNamed:@"apple_min"];
pSlider.maximumValueImage = [UIImage imageNamed:@"apple_max.png"];
[pSlider setThumbImage:[UIImage imageNamed:@"apple_thumb.png"]
forState:UIControlStateNormal];
[pSlider addTarget:self action:@selector(sliderValueChange:)
forControlEvents:UIControlEventValueChanged];
[self.view addSubview:pSlider];
- (void)sliderValueChange:(UISlider *)slider {
self.pShowValueLabel.text = [NSString stringWithFormat:@"亮度:%d", (int)slider.value];
self.pImageView.alpha = slider.value / 100;
}
UISwitch *pSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(220, 10, 10, 50)];
[pSwitch addTarget:self action:@selector(switchMethod:)
forControlEvents:UIControlEventValueChanged];
[self.view addSubview:pSwitch];
- (void)switchMethod:(UISwitch *)sender {
[self.pImageView setHidden:!sender.isOn];
}
NSArray *pArr = [NSArray arrayWithObjects:@"1", @"2", nil]; UISegmentedControl *pSegment = [[UISegmentedControl alloc] initWithItems:pArr]; [pSegment setFrame:CGRectMake(10, 240, 300, 40)]; [pSegment setSegmentedControlStyle:UISegmentedControlStyleBordered]; [pSegment setSelectedSegmentIndex:0]; [pSegment addTarget:self action:@selector(segmentMethod:) forControlEvents:UIControlEventValueChanged]; [self.view addSubview:pSegment];
self.pProgress = [[UIProgressView alloc] initWithFrame:CGRectMake(10, 360, 300, 30)];
self.pProgress.progressViewStyle = UIProgressViewStyleBar;
self.pProgress.trackTintColor = [UIColor redColor];
self.pProgress.progressTintColor = [UIColor greenColor];
[self.view addSubview:self.pProgress];
// 用計時器驅動進度變化
pTimer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(progressMethod:)
userInfo:nil
repeats:YES];
- (void)progressMethod:(id)sender {
self.progressValue += 0.1;
self.pProgress.progress = self.progressValue;
self.pProgressValueLabel.text =
[NSString stringWithFormat:@"加載:%.1f%%", self.progressValue * 100];
if (self.progressValue >= 1) {
self.progressValue = 0;
self.pProgressValueLabel.text = @"加載完成";
[pTimer invalidate]; // 記得停止計時器
}
}
這裡的 NSTimer 請注意前面文章提到的循環引用問題 —— 進度條邏輯結束後一定要 invalidate,否則控制器無法釋放。
self.pActivity = [[UIActivityIndicatorView alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
[self.pActivity setFrame:CGRectMake(10, 280, 45, 45)];
self.pActivity.hidesWhenStopped = YES;
[self.view addSubview:self.pActivity];
UIButton *pBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[pBtn setFrame:CGRectMake(10, 330, 45, 30)];
[pBtn setTitle:@"轉" forState:UIControlStateNormal];
[pBtn addTarget:self action:@selector(doRotate:)
forControlEvents:UIControlEventTouchUpInside];
pBtn.tag = 110;
[self.view addSubview:pBtn];
- (void)doRotate:(UIButton *)sender {
if (self.pActivity.isAnimating) {
[self.pActivity stopAnimating];
[sender setTitle:@"轉" forState:UIControlStateNormal];
} else {
[self.pActivity startAnimating];
[sender setTitle:@"停" forState:UIControlStateNormal];
}
}
這份代碼整理於 iOS 6 前後,直接拷貝到新項目中會遇到不少編譯警告或錯誤。常見的替換關係如下:
UITextBorderStyleRoundedRect → UITextBorderStyleRoundedRect 仍可用,但 iOS 7 之後更推薦直接用 layer 設置圓角。
NSTextAlignmentCenter(原文寫作 UITextAlignmentCenter)與 NSLineBreakByWordWrapping 是新版枚舉名。
pLabel.shadowColor 在 iOS 6.1 之後已廢棄,改用 NSShadow 或 attributedText。
[obj release] 在 ARC 下不應出現。
硬編碼的 frame 佈局在 iPhone 6 之後的各種屏幕尺寸下都會錯位,新項目應使用 Auto Layout 或至少做屏幕適配計算。