使用RubyMotion单击按钮时如何加载控制器?

时间:2012-11-04 14:32:51

标签: iphone ios ruby uiviewcontroller rubymotion

假设我有2个控制器A和B.

在A中我有:

def viewDidLoad
  super
  button = UIButton.buttonWithType UIButtonTypeRoundedRect
  button.setTitle "Open B", forState: UIControlStateNormal
  button.addTarget(self, action: :open_b, forControlEvents: UIControlEventTouchUpInside)
  self.view.addSubview button
end

def open_b
  # ?????
end

在B中我有另一个有自己逻辑的视图,这并不重要。

我想在点击按钮时打开B.我应该怎么做呢?

对于任何有iOS经验的人来说,这一定是显而易见的,但我找不到你应该怎么做。任何指针都表示赞赏。 Objectve-C中的解决方案是可以接受的,即使我更喜欢使用RubyMotion,也可以获得我的支持。

2 个答案:

答案 0 :(得分:7)

以下是使用模态视图控制器的方法:

app_delegate.rb:

class AppDelegate
  def application(application, didFinishLaunchingWithOptions:launchOptions)
    @window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds)
    @window.rootViewController = MyViewA.alloc.init
    @window.makeKeyAndVisible
    true
  end
end

viewa.rb:

class MyViewA < UIViewController

  def viewDidLoad
    super
    button = UIButton.buttonWithType UIButtonTypeRoundedRect
    button.setTitle "Open B", forState: UIControlStateNormal
    button.frame = [[10, 50], [300, 50]]
    button.addTarget(self, action: "open_b", forControlEvents: UIControlEventTouchUpInside)
    self.view.addSubview button
  end

  def open_b
    view_b = MyViewB.alloc.init
    view_b.delegate = self
    self.presentViewController view_b, animated:true, completion:nil
  end

  def done_with_b
    self.dismissViewControllerAnimated true, completion:nil
  end

end

viewb.rb:

class MyViewB < UIViewController

  attr_accessor :delegate

  def viewDidLoad
    super
    button = UIButton.buttonWithType UIButtonTypeRoundedRect
    button.setTitle "Return to A", forState: UIControlStateNormal
    button.frame = [[10, 50], [300, 50]]
    button.addTarget(self, action: "press_button", forControlEvents: UIControlEventTouchUpInside)
    self.view.addSubview button
  end

  def press_button
    delegate.done_with_b
  end

end

答案 1 :(得分:2)

以下是有关如何执行此操作的示例:https://github.com/IconoclastLabs/rubymotion_cookbook/tree/master/ch_2/11_navbarbuttons

具体来说,您的方法将使用此部分:

def performAdd
    @secondary_controller = SecondaryController.alloc.init
    self.navigationController.pushViewController(@secondary_controller, animated:'YES')
end

我强烈建议您在需要一些基础知识时参考这个回购(是的,这是我的)!

http://iconoclastlabs.github.com/rubymotion_cookbook/

希望能为你做到这一点!