如何在iPhone編程中以編程方式在UIView
上添加UITextField
?以編程方式在UIView上添加UITextField
UITextField* text;
UIView* view = [[UIView alloc]init];
[view addSubview:???];
如何在iPhone編程中以編程方式在UIView
上添加UITextField
?以編程方式在UIView上添加UITextField
UITextField* text;
UIView* view = [[UIView alloc]init];
[view addSubview:???];
的Objective-C:
CGRect someRect = CGRectMake(0.0, 0.0, 100.0, 30.0);
UITextField* text = [[UITextField alloc] initWithFrame:someRect];
UIView* view = [[UIView alloc] initWithFrame:someRect];
[view addSubview:text];
斯威夫特:
let someFrame = CGRect(x: 0.0, y: 0.0, width: 100.0, height: 30.0)
let text = UITextField(frame: someFrame)
let view = UIView(frame: someFrame)
view.addSubview(text)
如果你想要一個看起來像在Interface Builder中的文本字段:
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 200, 300, 40)];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.font = [UIFont systemFontOfSize:15];
textField.placeholder = @"enter text";
textField.autocorrectionType = UITextAutocorrectionTypeNo;
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDone;
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField.delegate = self;
[self.view addSubview:textField];
[textField release];
'contentVerticalAlignment'是這裏至關重要的元素 – 2013-02-20 23:11:16
+1 @NathanielSymer:我花了1個小時計算出來,直到我在這裏看到您的評論... :)謝謝.. – 2013-03-22 11:06:05
非常感謝@ioshero這真的是一個很好的答案...恕我直言,我認爲應該被標記爲一個正確的答案。你所涵蓋的UITextField的不同參數的事實是非常棒的。再次感謝您的回答。 – Jiraheta 2013-09-05 20:37:47
在斯威夫特2.0:
let sampleTextField = UITextField(frame: CGRectMake(20, 100, 300, 40))
sampleTextField.placeholder = "Enter text here"
sampleTextField.font = UIFont.systemFontOfSize(15)
sampleTextField.borderStyle = UITextBorderStyle.RoundedRect
sampleTextField.autocorrectionType = UITextAutocorrectionType.No
sampleTextField.keyboardType = UIKeyboardType.Default
sampleTextField.returnKeyType = UIReturnKeyType.Done
sampleTextField.clearButtonMode = UITextFieldViewMode.WhileEditing;
sampleTextField.contentVerticalAlignment = UIControlContentVerticalAlignment.Center
sampleTextField.delegate = self
self.view.addSubview(sampleTextField)
UITextField *mycooltext=[[UITextField alloc]initWithFrame:CGRectMake(10, 70, 50, 50)];
[email protected]"I am cool";
[self.View addSubView:mycooltext];
什麼框架? – galactikuh 2016-01-24 18:47:56
@galactikuh你是什麼意思?框架是放置視圖的矩形。 – Skie 2016-01-25 09:10:32
如果這是答案的重要部分,那麼框架的創建應該包含在代碼中。 – galactikuh 2016-01-25 14:14:27