您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 控制元件建立與常用屬性大全:從 UIImageView 到 UIActivityIndicatorView

編輯:iOS 開發綜合

這份筆記把 UIKit 常用控件的建立方式與主要屬性整理在一起,作為開發時的對照表。全部以程式碼建立,不使用 storyboard,方便直接複製套用。

1. UIImageView

// 取得圖片
UIImage *pImage = [UIImage imageNamed:@"sea.png"];

// 以內容圖片建立 ImageView
self.pImageView = [[UIImageView alloc] initWithImage:pImage];

// 加入父視圖
[self.view insertSubview:self.pImageView atIndex:0];

2. UILabel

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 release];

3. UITextField

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];

對應的 UITextFieldDelegate 常用方法:

// 按下 Return 鍵時收起鍵盤
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

// 點擊背景收起鍵盤
- (IBAction)backgroundTap:(id)sender {
    [_numberField resignFirstResponder];
    [_codeField resignFirstResponder];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

// 限制輸入長度
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
    int MAX_LENGTH = 10;
    NSMutableString *newString = [NSMutableString stringWithString:textField.text];
    [newString replaceCharactersInRange:range withString:string];
    return ([newString length] <= MAX_LENGTH);
}

4. UIButton

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 { }

5. 自製核取方塊(Checkbox)

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;   // 切換選取狀態,圖片自動跟著換
}

6. UISlider

UISlider *pSlider = [[UISlider alloc] initWithFrame:CGRectMake(10, 195, 300, 20)];
pSlider.minimumValue = 0;
pSlider.maximumValue = 100;
pSlider.continuous = YES;
pSlider.value = 50;

self.pImageView.alpha = pSlider.value / 100;   // 用滑桿控制透明度

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;
}

7. UISwitch

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];
}

8. UISegmentedControl

NSArray *pArr = @[@"1", @"2"];
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];

9. UIProgressView

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];
    }
}

10. UIActivityIndicatorView

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];
    } else {
        [self.pActivity startAnimating];
    }
    [sender setTitle:(self.pActivity.isAnimating ? @"停" : @"轉")
            forState:UIControlStateNormal];
}

版本提醒

這份清單反映了較早期 iOS 的 API。新專案請注意以下變動:UITextBorderStyle 已改名為 UITextFieldBorderStyle;UISegmentedControlStyle 與 buttonWithType:UIButtonTypeRoundedRect 的樣式概念已被弱化;numberOfLines 之類的屬性不變,但字型設定建議改用 preferredFontForTextStyle: 搭配 adjustsFontForContentSizeCategory 以支援動態字型。另外,全部改用 ARC 後,範例中的 release 呼叫都應刪除。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved