I have an app that has a main view that acts as a view controller. This main view has 3 buttons on it.开发者_StackOverflow社区 I have 3 subviews that I swap in and out of this main view, controlled by the 3 buttons. Each of the subviews has a button on it. When this button is pressed I want it to disable the 3 buttons on the main view until the button is pressed again. Is there a way to send a message between the views to disable the buttons?
This sounds like a toggle to me. More like a setting. If you think about it, this should go in NSUserDefaults
. And when you that particular view is coming on, probably in viewWillAppear:
or viewDidAppear:
, do this,
BOOL controlsEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:@"ControlsEnabledKey"];
button1.enabled = controlsEnabled;
button2.enabled = controlsEnabled;
button3.enabled = controlsEnabled;
To save the value on that button press,
BOOL controlsEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:@"ControlsEnabledKey"];
[[NSUserDefaults standardUserDefaults] setBool:!controlsEnabled forKey:@"ControlsEnabledKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
note Since the boolForKey:
will return NO
if the key is not found, I suggest you set the value to YES
when the application starts if you want the controls to be enabled at launch.
Use NSNotifications to post a notification that the buttons were pressed.
[[NSNotificationCenter defaultCenter] postNotificationName:@"Button1Pressed" object:self userInfo:info];
And then add observers such that they listen to these notifications.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(buttonPress:) name:@"Button1Pressed" object:nil];
Now implement buttonPress
Read HERE for the NSNotification manual and learn to use it .
Set the main view/controller as the delegate of the inner views, define a protocol in which you define a method, say, toggleMainButtons
, have the VC conform to that protocol and implement the message. On the buttons, addTarget:self.delegate action:@selector(toggleMainButtons) forControlEvents:UIControlEventTouchUpInside
.
精彩评论