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

iph*_*ler 4 xcode uiviewcontroller

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

Bjö*_*lek 8

使用此签名在视图控制器中创建一个新方法:-(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];
}
Run Code Online (Sandbox Code Playgroud)