单击按钮时,如何将 UIView 添加为 UIViewController 的子视图? [英] How can I add a UIView as a subview of UIViewController when a button clicked?
问题描述
在我的应用程序中,每当用户点击我的主 UIViewController 中的按钮时,我都需要动态添加 UIView.我该怎么做?
In my app I need to add a UIView dynamically whenever user taps on a button in my main UIViewController. How can I do this?
推荐答案
在您的视图控制器中使用此签名创建一个新方法:-(IBAction) buttonTapped:(id)sender
.保存您的文件.转到 Interface Builder 并将您的按钮连接到此方法(按住 Control 单击并从您的按钮拖动到视图控制器 [可能是您的文件的所有者] 并选择 -buttonTapped
方法).然后实现方法:
Create a new method in your view controller with this signature: -(IBAction) buttonTapped:(id)sender
. Save your file. Go to Interface Builder and connect your button to this method (control-click and drag from your button to the view controller [probably your File's owner] and select the -buttonTapped
method).
Then implement the method:
-(IBAction) buttonTapped:(id)sender {
// create a new UIView
UIView *newView = [[UIView alloc] initWithFrame:CGRectMake(10,10,100,100)];
// do something, e.g. set the background color to red
newView.backgroundColor = [UIColor redColor];
// add the new view as a subview to an existing one (e.g. self.view)
[self.view addSubview:newView];
// release the newView as -addSubview: will retain it
[newView release];
}
这篇关于单击按钮时,如何将 UIView 添加为 UIViewController 的子视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!