0

Here I create two views(bar and icon) and I would like to make one call to @window.addSubview to add them both.

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

I would like something like this:

@window.addSubview bar, icon

or

@window.addSubview [bar,icon]

I realize the difference is nominal but it seems like there should be a way to call addSubview on several views at once.

Josh
  • 5,631
  • 1
  • 28
  • 54

2 Answers2

1

I would say you are just begging to trip yourself and others up at a latter date by doing this, but if you must you can just reopen UIView and define the method yourself

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

This should allow

@window.addSubviews [view_a, view_b]

# OR

@window.addSubviews view_a, view_b

To try it out here is a full example

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
Paul.s
  • 38,494
  • 5
  • 70
  • 88
0

As far as I know there isn't a single method to do what you want. The normal ruby way would be this :

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

or even shorter :

[bar, icon].each{|v| @window.addSubView(v) }
cmrichards
  • 1,725
  • 1
  • 19
  • 28
  • That works, but it is just as bulky as two separate calls. I was hoping for something a bit more elegant. – Josh Jul 15 '12 at 21:36
  • 1
    the addSubview method add a subview, not add an array of subviews. If you are not happy with that, you can implement addSubviews methods and use it instead. – siuying Jul 16 '12 at 00:43
  • @siuying is correct, the addSubView method is an Apple SDK method and has nothing to do with RubyMotion. If you want a method that takes an array instead, you'd need to implement it yourself. – bensie Jul 16 '12 at 17:32