【问题标题】:Action not being called when UIBarButtonItem tapped点击 UIBarButtonItem 时未调用操作
【发布时间】:2012-06-15 20:00:48
【问题描述】:

注意:我只在模拟器上测试过。

我想在代码中添加目标操作,而不是在 Interface Builder 中将其连接为 IBAction。

theButton 位于左上角的导航栏上,在 IB 中创建。

步骤:

  1. theButton 声明为 IBOutlet 并在 IB 中连接。

  2. 添加到viewDidLoad:

    self.theButton.target = self;
    self.theButton.action = @selector(theAction);
    
  3. 我正在通过这个测试theAction

    - (void)theAction {
    NSLog(@"theAction called");
    //do some other stuff
    }
    

当我在模拟器中点击theButton 时,什么也没有发生。我根本没有看到 NSLog 语句。

我错过了什么?

【问题讨论】:

    标签: iphone ios cocoa-touch uibarbuttonitem


    【解决方案1】:

    您是否已将操作连接到 interface-builder 中的按钮?

    如果不是,您应该在 .h 文件中声明该操作

    -(IBAction)theAction;
    

    更改 .m 文件上的操作名称

    -(IBAction)theAction{
    
    }
    

    并将操作精细地连接到界面生成器中的按钮。

    【讨论】:

    • 不需要,因为它是通过 self.theButton.target = self; 以编程方式完成的。和 self.theButton.action = @selector(theAction);
    • 编辑了我的答案以供编程使用。
    • 请注意,UIBarButtonItem 不会响应 addTarget:action:forControlEvents: 方法
    • 仅供未来的读者阅读。编译器在 Xcode 4 中给我一个错误。它不喜欢星号。
    • 我在 7.1 上遇到了同样的问题。在 IB 中 UIBarButtonItem 通过 Ctrl+Drag 链接到 IBAction 但它没有被调用。在 8.1 上它可以工作。
    【解决方案2】:

    改变你的功能如下:

    -(IBAction)theAction{
        NSLog(@"theAction called");
        //do some other stuff
    }
    

    如果你像“@selector(theAction:);”一样调用 然后改变如下功能:

    -(IBAction)theAction:(id)sender{
        NSLog(@"theAction called");
        //do some other stuff
    }
    

    希望对你有所帮助。

    如果有任何困难,请告诉我。

    【讨论】:

      【解决方案3】:

      想通了。跟我的配置有关。我正在使用一个标签栏控制器,它对多个标签使用相同的视图控制器。每个视图控制器为某些选项卡项显示不同的过滤数据。

      因此,在这样的配置中,您必须确保为标签栏项目包含的每个视图控制器连接 IBOutlets。我只连接了一个,这就是为什么它不适用于某些选项卡项。

      【讨论】:

        猜你喜欢
        • 2015-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-26
        • 2017-07-29
        相关资源
        最近更新 更多