Question

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];
}
Was it helpful?

Solution

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.

OTHER TIPS

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];
    } 
}

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;
}

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];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top