【问题标题】:Can't make UIBarButtonItem's action work无法使 UIBarButtonItem 动作起作用
【发布时间】:2026-01-10 02:15:01
【问题描述】:

我有一个控制器和一个按钮。单击按钮时,我想显示UIAlertView。我无法工作的是UIBarButtonItemaction参数。

在我的控制器中

class TapController < UIViewController
  def alert
    alert = UIAlertView.new
    alert.message = "It's working"
    alert.show
  end

  def viewDidLoad
    super
    self.view.backgroundColor = UIColor.whiteColor
    right_button = UIBarButtonItem.alloc.initWithTitle("Go Deeper",
                                                       style:UIBarButtonItemStyleBordered,
                                                       target:self,
                                                       action:'alert')
    self.navigationItem.rightBarButtonItem = right_button
  end
end

我的app/app_delegate.rb

class AppDelegate
  def application(application, didFinishLaunchingWithOptions:launchOptions)
    #UIScreen is the display the app runs on
    @window = UIWindow.new.initWithFrame(UIScreen.mainScreen.bounds)
    @window.makeKeyAndVisible

    controller = TapController.alloc.initWithNibName(nil, bundle: nil)
    @window.rootViewController = UINavigationController.alloc.initWithRootViewController(controller)

    true
  end
end

所以很简单,但是 UIBarButtonItem 的 target 或 action 属性并没有按预期工作。

【问题讨论】:

    标签: cocoa-touch rubymotion


    【解决方案1】:

    这是你的问题。在您的应用委托中,您需要在 UIWindow 上调用 alloc 而不是 new

    @window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds)
    

    【讨论】:

    • 哦! AFAIK 新方法是一个 OBJ c 速记,它执行 allocinit。你知道为什么使用new会失败吗?
    • 非常感谢!完全错过了。
    • 我不知道为什么它用new 失败,但我只看到它在这种情况下用alloc.init 写。