我想隐藏按钮Objective-C ios?

时间:2014-05-06 17:55:02

标签: ios button uibutton

当我在.h上定义按钮时,它可以正常工作,但是当我编码时按钮不起作用。

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIImage *buttonImage = [UIImage imageNamed:@"nl.png"];

    //create the button and assign the image
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame=CGRectMake(230,302,32,32);
    [button setImage:buttonImage forState:UIControlStateNormal];


    //create a UIBarButtonItem with the button as a custom view
    //UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];

    [button addTarget:self action:@selector(clickActionItem) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

-(void)btnClicked
{
    [self.button Sethidden:YES]:
    self.button.hidden=YES;
    _button.hidden=YES;
}

但不工作

2 个答案:

答案 0 :(得分:1)

问题

问题是您在UIButton方法上创建viewDidLoad并且您没有保存实例,因此您无法访问它。另一个问题是,您正在为按钮selector提供另一种方法。

解决方案

在选择器中更改目标并添加UIButton作为参数,就像下面的代码一样

[button addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];

方法btnClicked采用按钮传递的button实例

-(void)btnClicked:(UIButton *)button
{
    [button sethidden:YES];
}

这应该可以解决问题。

答案 1 :(得分:0)

@implementation YourView{
    UIButton *button;
}
- (void)viewDidLoad
{
    [super viewDidLoad];

            UIImage *buttonImage = [UIImage imageNamed:@"nl.png"];

            //create the button and assign the image
            button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame=CGRectMake(230,302,32,32);
            [button setImage:buttonImage forState:UIControlStateNormal];


            //create a UIBarButtonItem with the button as a custom view
            //UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc]       initWithCustomView:button];

            [button addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:button];
}

-(void)btnClicked
{
    [button setHidden:YES]; 
}

您的代码没有提供足够的信息来查看您打算做什么。你还可以提供头文件吗?