【问题标题】:I want to hide button Objective-C ios?我想隐藏按钮 Objective-C ios?
【发布时间】:2014-05-06 17:55:02
【问题描述】:

当我在.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;
}

但是不行

【问题讨论】:

  • [self.button Sethidden:YES]: 好吧,倒转大写,用“:”代替“;”。请问,你的真实密码是什么?什么时候调用“btnClicked”?
  • 你的按钮是一个局部变量,你不能通过self.button在其他方法中得到它

标签: ios button uibutton


【解决方案1】:

问题

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

解决方案

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

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

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

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

这应该可以解决问题。

【讨论】:

    【解决方案2】:
    @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]; 
    }
    

    您的代码没有提供足够的信息来查看您打算做什么。能否也提供一下头文件?

    【讨论】:

    • 这种方式没有self.button属性,只有button实例变量。它也会泄漏,button 应该是 __weak 引用,因为它的父视图将保留它。
    • @RolandKákonyi __weak 不需要在这里避免泄漏。视图控制器已经拥有强大的所有权,因为它位于self.view.subviews 中。当视图控制器被释放时,这两个引用都会被清除。这里习惯使用弱引用,因为视图控制器正在引用对象,但不需要真正拥有它。
    猜你喜欢
    • 1970-01-01
    • 2015-04-28
    • 2014-10-01
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-25
    相关资源
    最近更新 更多