简体   繁体   中英

Can't programmatically hide UIButton created with IB

My iOS UIButton is correctly linked from IB to an IBOutlet in my view controller, as I can change its title from my code. Ie:

[self.myButton setTitle:@"new title" forState:UIControlStateNormal]; //works

However,

[self.myButton setHidden:YES]; //doesn't work
//or
self.myButton.hidden = YES; //doesn't work

What's going on? How can I make myButton disappear?

Update: some additional info

Here's the code related in to my UIButton:

in my.h file

IBOutlet UIButton *myButton;
-(IBAction)pushedMyButton:(id)sender;
@property (nonatomic,retain) UIButton *myButton;

in my.m file

@synthesize myButton;
- (void)pushedMyButton:(id)sender{
    self.myButton.hidden = YES;
}
- (void)dealloc{
    [self.myButton release];
}

Ok I found a workaround that works but I still don't know why my original code wasn't working in the first place. I used Grand Central Dispatch to dispatch a block containing the hide call on the main queue, like this:

dispatch_async(dispatch_get_main_queue(), ^{
    self.myButton.hidden = YES; //works
});

Interesting. None of the initial code in my IBOutlet was wrapped in GCD blocks though. Any ideas?

这应该工作,尝试重命名并隐藏它只是为了检查彼此顶部没有两个按钮。

User Interface (UI) API (UIKit ...) methods have to be run on Main Thread!

So this will run on Main thread (as *dispatch_get_main_queue*):

dispatch_async(dispatch_get_main_queue(), ^{
    self.myButton.hidden = YES; //works
});

BUT usually we do something like this:

[self performSelectorOnMainThread:@selector(showButton) withObject:nil waitUntilDone:NO];

[self performSelectorOnMainThread:@selector(hideButton) withObject:nil waitUntilDone:NO];

-(void)showButton
{
    myButton.hidden = NO;
}

-(void)hideButton
{
    myButton.hidden = YES;
}

As per Apple's documentation: http://developer.apple.com/library/ios/#documentation/uikit/reference/uiview_class/uiview/uiview.html " Threading Considerations Manipulations to your application's user interface must occur on the main thread. Thus, you should always call the methods of the UIView class from code running in the main thread of your application. The only time this may not be strictly necessary is when creating the view object itself but all other manipulations should occur on the main thread. "

我有同样的问题,发现解决方案是将隐藏在正确的位置,在我的情况下在viewDidLoad函数中。

What worked for me is putting the manipulating code in viewDidLoad instead of initWithNibName, like this:

- (void)viewDidLoad
{
    btnRestart.enabled = false;
}

Had the same problem: button.hidden = YES didn't hide.

Solved it when I defined it in the.h file using @property and @synthesize in the.m file thus making it self.button.

Now self.button.hidden = YES works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM