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

时间:2012-01-23 06:53:34

标签: iphone objective-c xcode uiview

当我在我的超级视图中创建UIView时,我想在此视图中添加一个按钮作为退出按钮。 所以当按下时,它会从我的超视图中删除这个UIView,我该怎么做? 按下按钮时,以编程方式创建该视图中的视图和按钮

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

3 个答案:

答案 0 :(得分:4)

在创建视图的类中,添加如下函数:

//tag for subview - make it unique
#define SUBVIEW_TAG 9999 

- (void) handleExit
{
    UIView * subview = [self.view viewWithTag:SUBVIEW_TAG];
    [subview removeFromSuperview];
}

并在创建子视图时执行:

- (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!
}

答案 1 :(得分:1)

以下是您的代码:

        self->myButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self-> myButton = CGRectMake(60, 6, 180, 30);
    [self-> myButton setTitle:@"MyButton" forState:UIControlStateNormal];
    [self-> myButton setTextColor:[UIColor whiteColor]];
    self-> myButton = 1;
    [self-> myButton addTarget:self action:@selector(myButtonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self-> myButton];

更改按钮放置的坐标

myButtonTouchUpInside 方法实现中,

[self removeFromSuperview];

希望这是你想要的......

答案 2 :(得分:1)

您甚至可以隐藏视图或[self removeFromSuperview];