【问题标题】:iOS7 Call an IBAction method also from ViewDidLoadiOS7 也从 ViewDidLoad 调用 IBAction 方法
【发布时间】:2014-04-19 21:04:54
【问题描述】:

所以我有一个带有按钮的视图,该按钮调用具有此方法签名的 IBAction 方法,并且从按钮上可以正常工作。

-(IBAction)getCurrentConditions:(id)sender

我还想从 ViewDidLoad 中调用相同的方法。我在 (id)sender 参数中传递什么,因为我不需要从 ViewDidLoad 传递任何东西。

【问题讨论】:

  • [self getCurrentConditions:nil],除非在getCurrentConditions 中使用sender

标签: ios objective-c methods


【解决方案1】:

发送者通常是发送消息的“IBOutlet”,例如 UIButton。因此,您可以将该按钮链接到您的视图控制器并将其设置为发送者。或者,如果您对发件人什么都不做,您可以发送 nil。

【讨论】:

    【解决方案2】:

    如果您有对按钮的属性引用,则传递nil 或传递self.someButton。当然,传递nil 仅在该方法不需要发送者时才有效。话又说回来,如果该方法不需要发送者,为什么还要费心设置参数呢?

    [self getCurrentCondition:self.someButton];
    

    [self getCurrentCondition:nil];
    

    或者将签名改为:

    - (IBAction)getCurrentCondition {
        // Do stuff that doesn't need the sender
    }
    

    【讨论】:

      【解决方案3】:

      通常,IBAction 方法从 .xib 文件中调用,但您可以使用选择器从实现文件中的任何位置调用它

      [self performSelector:@selector(getCurrentConditions:) withObject:self.curConditionBtn afterDelay:0.0f];
      

      【讨论】:

      • 好奇——为什么使用performSelector:withObject:afterDelay:而不是直接调用方法?
      • 只是另一种调用方法的方式......也可以直接调用方法......
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多