Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS creating a reusable view woes

I am trying to create a custom view, with a nib and attendant .h/.m files, and then create multiple instances of that view via IB, and use them as subviews of another view.

  1. I created the .h/.m files
  2. I created the xib.
  3. For the xib, I specify the class name in IB.
  4. Add some labels to the xib (the values for which will be programmatically changed)
  5. I drag a simple view in storyboard into my container view.
  6. I set the class of the dragged view to the class i specified for the xib.

I do steps 5 and 6 multiple times, once for each view I want. Eventually I would connect these views to IBOutlets on the parent view class.

Obviously I am doing something wrong because I am not seeing my labels in the custom view. I suspect I need to associate the nib with the view directly, much like you do with collection/table view, but I haven't found where to do this.

What is the correct way to do this? I suppose I could add views programmatically, but then how do I handle the layout for various devices (e.g. iphone 4 vs 5)?

like image 210
hvgotcodes Avatar asked Jan 14 '23 10:01

hvgotcodes


1 Answers

What I outline below appears to work

1) Create the xib and .h/.m files for your custom view.
1a) Assuming you need IBOutlets to view elements over which you want control, give the File's Owner the class name defined in your .h file in the identity inspector.

2) In .h file define a property

@property (nonatomic, retain) IBOutlet UIView *contentView;

2a) define outlets for all the subviews in your xib, to which you want programmatic access.

3) In the .m file synthesize the property and do

- (void)awakeFromNib
{
    NSLog(@"awake from nib");
    [[NSBundle mainBundle] loadNibNamed:@"yourNibName" owner:self options:nil];
    [self addSubview:self.contentView];
}

4) Drag empty views from the palette into their container in the storyboard. Change the class of these views to the class name defined in your .h file.

When you run your app you should see the contents of the xib in your subviews.

5) You can now define outlets to your custom subview instances in the .h file of the container view, and connect them as usual in the storyboard.

like image 69
hvgotcodes Avatar answered Jan 22 '23 07:01

hvgotcodes