How to programmatically disable/enable a UIBarButt

2019-07-08 03:48发布

问题:

I currently have a button called continueButton that has been assigned to a UIBarButtonItem button in a Storyboard file. I've declared the button as such:

- (IBAction)continueButton;

When the view loads, I want the button to disable itself, so that there can be no user input unless a command is called that re-enables user input for the button. How would I go about doing this? I'm trying to use the function [continueButton setEnabled:YES]; to disable/enable the button programmatically, but it doesn't work properly.

回答1:

You haven't exposed the UIBarButtonItem to your code. For the properties of the control to be accessible it either needs to be connected to an IBOutlet (bridge between XIB and code) as hw731 said, or created programmatically in the first place. An action is more like binding a method to an event raised by the control.

If you cant see the option for an Outlet or Outlet collection when making the connection its likely you are in the .m file instead of the .h file.



回答2:

After reading through some of the comments, I realized that I wasn't supposed to setup the UIBarButtonItem as a IBAction button, but through an IBOutlet. After doing so, and reconnecting the button in Storyboards, the command I was trying before, worked.

[continueButton setEnabled:NO];

or (for enabling the button):

[continueButton setEnabled:YES];