简体   繁体   English

如果IBAction中的其他语句-iOS

[英]If Else Statement in IBAction - iOS

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. 我已经构造了if-else语句来使UIButton之前充当切换按钮,但是这组代码似乎更具挑战性。 I have 2 separate IBActions right now, one called open, the other called close. 我现在有2个独立的IBAction,一个称为打开,另一个称为关闭。 I would like to make it one IBAction that works as a toggle via an if-else statement. 我想使它成为一个通过if-else语句进行切换的IBAction。 Here is the code for both IBActions. 这是两个IBAction的代码。

- (IBAction)actionOpen:(id)sender {
    [self.flatDatePicker show];
}

- (IBAction)actionClose:(id)sender {
    [self.flatDatePicker dismiss];
}

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. 或者,在flatDatePicker上使用一个属性(该属性会告诉您该属性是否可见),而不是其他属性。

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 在标题中为datePickerShowing创建BOOL类型

@property (nonatomic,assign) BOOL datePickerShowing;

Synthesize it in your .m file 将其合成到您的.m文件中

@synthesize datePickerShowing;

Set this to NO in your init method. 在您的init方法中将此设置为NO。 datePickerShowing = NO;

In your IBAction: 在您的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 . 我可以想象self.flatDatePicker是一个UIDatePicker对象,该对象继承自UIView There is no need for a separate state flag, simply examine the UIView.hidden property: 不需要单独的状态标志,只需检查UIView.hidden属性:

- (IBAction)actionToggle:(id)sender {
    if (self.flatDatePicker.hidden)
        [self.flatDatePicker show];
    else
        [self.flatDatePicker dismiss];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM