iphone - 如何以编程方式将退出按钮添加到 UIView

标签 iphone objective-c xcode uiview

当我在我的 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/

相关文章:

iphone - iphone 与 mac 通讯的最佳方式?

iphone - IOS 5.0 及更高版本中的 UITextView 中不显示文本

objective-c - SiriKit:使用多个电话号码调用联系人

iOS 状态恢复日志警告而不是在模拟器中运行

iphone - iOS : Use a boolean in NSUserDefaults

ios - 在 UICollectionViewCell 中获取图像

objective-c - 报告 OSX 中的大小写不敏感(使用 OSXFuse)

ios - 在呈现另一个 View Controller 时,如何阻止 "from" View 变黑?

ios - 线程 1 : signal SIGABRT error in Swift

ios - Cordova 使用 Xcode SQLite 插件构建