Reputation: 418
I have constructed if-else
statement to make UIButtons act as a toggle before, but this set of code seems to be a little more challenging. I have 2 separate IBActions right now, one called open, the other called close. I would like to make it one IBAction that works as a toggle via an if-else
statement. Here is the code for both IBActions.
- (IBAction)actionOpen:(id)sender {
[self.flatDatePicker show];
}
- (IBAction)actionClose:(id)sender {
[self.flatDatePicker dismiss];
}
Upvotes: 0
Views: 345
Reputation: 130193
You don't have to create your own property for this, the flat picker already has one defined as:
@property(nonatomic,readonly) BOOL isOpen; // read only property, indicate in datepicker is open.
So...
- (IBAction)toggleFlatDatePicker {
if (self.flatDatePicker.isOpen) {
[self.flatDatePicker dismiss];
}else{
[self.flatDatePicker show];
}
}
Upvotes: 3
Reputation: 122391
I would imagine self.flatDatePicker
is a UIDatePicker
object, which inherits from UIView
. There is no need for a separate state flag, simply examine the UIView.hidden
property:
- (IBAction)actionToggle:(id)sender {
if (self.flatDatePicker.hidden)
[self.flatDatePicker show];
else
[self.flatDatePicker dismiss];
}
Upvotes: 1
Reputation: 9035
Create a BOOL
type in your header for datePickerShowing
@property (nonatomic,assign) BOOL datePickerShowing;
Synthesize it in your .m file
@synthesize datePickerShowing;
Set this to NO in your init method. datePickerShowing = NO;
In your IBAction:
if (datePickerShowing) {
[flatDatePicker dismiss];
datePickerShowing = NO;
} else {
[flatDatePicker show];
datePickerShowing = YES;
}
Upvotes: 1
Reputation: 77641
Set a property or something, like this...
// in the private extension
@property (nonatomic) BOOL flatDatePickerOpen;
Then do something like this...
- (IBAction)toggleFlatDatePicker {
if (self.flatDatPickerOpen) {
[self.flatDatePicker dismiss];
self.flatDatePickerOpen = NO;
} else {
[self.flatDatePicker show];
self.flatDatePickerOpen = YES;
}
}
You don't have to specify the sender part of the action either. If you're not using it then there's no need for it.
Alternatively, use a property on the flatDatePicker that tells you whether it is visible or not instead of the additional property.
Upvotes: 3