xcode 单击按钮时,如何将 UIView 添加为 UIViewController 的子视图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3994174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 19:52:01  来源:igfitidea点击:

How can I add a UIView as a subview of UIViewController when a button clicked?

xcodeuiviewcontroller

提问by iphoneStruggler

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?

在我的应用程序中,每当用户点击主 UIViewController 中的按钮时,我都需要动态添加 UIView。我怎样才能做到这一点?

回答by Bj?rn Marschollek

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 -buttonTappedmethod). Then implement the method:

在与此签名您的视图控制器创建一个新的方法:-(IBAction) buttonTapped:(id)sender。保存您的文件。转到 Interface Builder 并将您的按钮连接到此方法(按住 Control 单击并从您的按钮拖动到视图控制器 [可能是您的文件所有者] 并选择该-buttonTapped方法)。然后实现方法:

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