views:

265

answers:

2

I want to build up a sub-UIView in Interface Builder (contained within a UIScrollView) with some UILabels contained, I then want to programmatically "copy" this view adjust its left position (by multiples of its width) to achieve a "floating" left effect inside a UIScrollView. I then want to add this copied UIView back into the UIScrollView with different text for the UILabels.

The problem is I don't know how and if you can "copy" UIViews.

A: 

I'm very new to objective-c programming (and oo programming in general). One of the things that has been difficult for me to remember is that any time you find yourself wanting to "copy" something into multiple places it probably means you need to subclass something and then add new instances of your custom subclass. In this case I think you'd want to create a subclass of UIView and then use that custom view as needed?

Please note that I post this advice for what it's worth... I'm a total noob to objective-c just killing time waiting on help with one of my own questions!

codemonkey
A: 

You can try calling [view copy], but I wouldn't be surprised if that didn't work. You can probably use NSKeyedArchiver/NSKeyedUnarchiver to serialize/deserialize the view, but that's also pretty terrible.

Instead, you probably want to load multiple copies of the view:

  1. Move the view you want multiple copies of into its own nib.
  2. Make the nib "owned" by your object (whatever class you want to be responsible for loading it).
  3. Add an IBOutlet called "myView" or whatever, and assign it to your view.
  4. In your class, call something like

(and I have to stick a line here or markdown doesn't seem to like it)

-(UIView)makeMeANewMyView {
  // Load MyView.nib into the myView outlet.
  [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self];
  // Take ownership.
  UIView * view = [[self.myView retain] autorelease];
  self.myView = nil;
  return view;
}
tc.