Tim
Tim

Reputation: 4101

Disable UIButton programmatically

I'm stumped at why this code isn't working. I have a login button that I want to disable when the user isn't logged in.

I have a UIButton delared in my .h file like so:

   IBOutlet UIButton *myBtn;

I've set up a referencing outlet in Interface Builder to this button.

In my .m file, I've tried:

[myBtn setEnabled: NO];

and

myBtn.enabled = NO;

But neither of these disable the button in the conditional statement I'm in. (I want to disable the login button when the user successfully logs in)

I'm able to do this with two other buttons on the same screen, so I know the code is correct. I don't throw any errors, so I think the object exists. The references to myBtn change color in XCode, too, so it appears to be a valid reference.

I must be missing something. What am I doing wrong here? (I'm a Windows developer, relatively new at Objective-C)

Upvotes: 8

Views: 15513

Answers (5)

xRab
xRab

Reputation: 133

If you're looking for Swift3 solution

var myBtn = UIButton()
myBtn.isEnabled = true

Upvotes: 8

ytbryan
ytbryan

Reputation: 2694

If you are looking for swift code:

var button = UIButton()
button.enabled = false //disable the button

Upvotes: 1

Tim Walsh
Tim Walsh

Reputation: 1105

You should be setting up your button as a IBOutlet.

@property (weak, nonatomic) IBOutlet UIButton *myBtn;

That way you can connect that button in storyboards. Which could be your issue.

Then call this to disable.

[_myBtn setEnabled:NO];

Upvotes: 2

Vineet Singh
Vineet Singh

Reputation: 4019

Do try this ..

In .h :

@property(nonatomic,retain)UIButton *myBtn;

In .m :

@synthesize myBtn;

And then,replace your [myBtn setEnabled: NO]; code with [self.myBtn setEnabled: NO]; code.

Upvotes: 1

ssantos
ssantos

Reputation: 16526

It seems ok to me. Are you synthesizing the button? Try

self.myBtn.enabled = NO;

Upvotes: 9

Related Questions