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

前端之家收集整理的这篇文章主要介绍了xcode – 如何在单击按钮时将UIView添加为UIViewController的子视图?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的应用程序中,每当用户点击我的主UIViewController中的按钮时,我都需要动态添加UIView.我怎样才能做到这一点?

解决方法

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

猜你在找的Xcode相关文章