1.按鈕(Button)
- (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];
}
2.標籤欄(Label)
- (void)addLabel:(id)sender
{
//創建一個label
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);
//設置label的背景色爲透明色
pLabel.backgroundColor = [UIColor clearColor];
//把標籤添加到當前視圖
[self.view addSubview:pLabel];
//把創建的變量釋放
[pLabel release];
}
3.文本欄(textField)
- (void)addTextField:(id)sender
{
//創建TextField
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協議,實現鍵盤的彈回方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
//放當前的textField放棄第一響應者
[textField resignFirstResponder];
return YES;
}
遵循UITextFieldDelegate協議,實現控制文本欄字符串的輸入長度控制
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
//設置最大可輸入的字符長度
int MAX_LENGTH = 10;
NSMutableString *pNewString = [NSMutableString stringWithString:textField.text];
//完成range內字符串的替換
[pNewString replaceCharactersInRange:range withString:string];
//根據兩個的長度判斷,返回YES or NO.
return ([pNewString length] <= MAX_LENGTH);
}