如何在iPhone上通过编程添加标签和文本框

6
我该如何在iPhone程序中以编程方式添加标签和文本框? 我该如何为标签和文本框设置框架?
2个回答

17

以下代码创建了一个 UILabel 和一个 UITextField 并将它们添加到视图控制器的视图中。将此代码添加到 loadView 方法或视图控制器的其他位置。

// Create Label
UILabel *myLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 50, 200, 40)];
[myLabel setBackgroundColor:[UIColor clearColor]];
[myLabel setText:@"Hi Label"];
[[self view] addSubview:myLabel];
[myLabel release];

// Create Text Field
UITextField *myTextField = [[UITextField alloc] initWithFrame:CGRectMake(10, 100, 200, 40)];
[myTextField setBackgroundColor:[UIColor clearColor]];
[myTextField setText:@"Hi Text Field"];
[[self view] addSubview:myTextField];
[myTextField release];

你还可以使用设置方法设置其他属性。


1
UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(10, 10, 29, 40)];
[textField setBorderStyle:UITextBorderStyleRoundedRect];
[self.view addSubview:textField];

UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 29, 40)];
label.text = @"Custom Label";
[label setFont:[UIFont boldSystemFontOfSize:16]];
[self.view addSubview:m_label];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接