当我在我的 super View 中创建一个 UIView 时,我想向该 View 添加一个按钮作为退出按钮。 所以当按下时,它会从我的 super View 中删除这个 UIView,我应该怎么做? 该 View 中的 View 和按钮是在按下按钮时以编程方式创建的
- (IBAction)skillButtonPressed:(UIButton *)sender
{
UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(40, 130, 240, 232)];
UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[cancelButton setFrame:CGRectMake(0, 0, 32, 32)];
[cancelButton setTitle:@"x" forState:UIControlStateNormal];
[myView addSubview:cancelButton];
[self.view addSubview:myView];
}
最佳答案
在创建 View 的类中,添加如下函数:
//tag for subview - make it unique
#define SUBVIEW_TAG 9999
- (void) handleExit
{
UIView * subview = [self.view viewWithTag:SUBVIEW_TAG];
[subview removeFromSuperview];
}
创建 subview 时:
- (IBAction)skillButtonPressed:(UIButton *)sender
{
UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(40, 130, 240, 232)];
UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[cancelButton addTarget:self action:@selector(handleExit) forControlEvents:UIControlEventTouchUpInside];
[cancelButton setFrame:CGRectMake(0, 0, 32, 32)];
[cancelButton setTitle:@"x" forState:UIControlStateNormal];
[myView addSubview:cancelButton];
[myView setTag:SUBVIEW_TAG];
[self.view addSubview:myView];
//don't forget to release if you are not using ARC!
}
关于iphone - 如何以编程方式将退出按钮添加到 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8968115/