2010-04-28 27 views

Trả lời

29

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

Swift:

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) 
+0

Các khung là gì? – galactikuh

+0

@galactikuh ý bạn là gì? Khung là hình chữ nhật trong đó lượt xem của bạn sẽ được đặt. – Skie

+0

nếu đây là một phần quan trọng của câu trả lời, có vẻ như việc tạo khung nên được bao gồm trong mã của bạn. – galactikuh

238

Nếu bạn muốn một trông như lĩnh vực văn bản trong giao diện người xây dựng:

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

'contentVerticalAlignment' là yếu tố quan trọng ở đây –

+0

+1 @NathanielSymer: Tôi đã dành 1 giờ để tìm cho đến khi tôi thấy nhận xét của bạn ở đây ... :) Cảm ơn .. –

+1

cảm ơn to @ioshero đây thực sự là một câu trả lời hay ... IMHO Tôi nghĩ rằng nên được đánh dấu là câu trả lời chính xác. thực tế bạn bảo vệ rất nhiều các thông số khác nhau của UITextField chỉ là tuyệt vời. Một lần nữa, cảm ơn bạn đã trả lời. – Jiraheta

1

Trong Swift 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) 
2
UITextField *mycooltext=[[UITextField alloc]initWithFrame:CGRectMake(10, 70, 50, 50)]; 
[email protected]"I am cool"; 
[self.View addSubView:mycooltext]; 
Các vấn đề liên quan