Rubymotion:如何通过一个addSubview调用将2个子视图添加到视图中?

时间:2012-07-15 21:06:22

标签: ruby rubymotion

在这里,我创建了两个视图(条形图标和图标),我想打电话给@window.addSubview添加它们。

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

    bar = UIView.alloc.initWithFrame [[0, 0], [320, 100]]

    icon= UIImageView.alloc.initWithFrame([[100,0], [100,100]])

    @window.addSubview bar   # I have two calls to addSubview
    @window.addSubview icon

  true
  end
end

我想要这样的事情:

@window.addSubview bar, icon

@window.addSubview [bar,icon]

我意识到差异是名义上的,但似乎应该有办法同时在几个视图上调用addSubview

2 个答案:

答案 0 :(得分:1)

我会说你只是乞求通过这样做来绊倒自己和其他人,但如果你必须,你可以重新打开UIView并自己定义方法

class UIView
  def addSubviews *views
    views.flatten.each { |view| addSubview view }
  end
end

这应该允许

@window.addSubviews [view_a, view_b]

# OR

@window.addSubviews view_a, view_b

试试这里是一个完整的例子

class AppDelegate
  def application(application, didFinishLaunchingWithOptions:launchOptions)

    @window = UIWindow.alloc.initWithFrame UIScreen.mainScreen.bounds
    @window.makeKeyAndVisible

    view_a = UIView.alloc.initWithFrame [[100, 100], [100, 100]]
    view_a.backgroundColor = UIColor.greenColor

    view_b = UIView.alloc.initWithFrame [[200, 200], [100, 100]]
    view_b.backgroundColor = UIColor.redColor

    @window.addSubviews [view_a, view_b]

    true
  end
end

class UIView
  def addSubviews *views
    views.flatten.each { |view| addSubview view }
  end
end

答案 1 :(得分:0)

据我所知,没有一种方法可以做你想要的。正常的红宝石方式是:

[bar,icon].each do |view|
  @window.addSubview view
end  

甚至更短:

[bar, icon].each{|v| @window.addSubView(v) }