Peter Warbo
Peter Warbo

Reputation: 11700

Custom UIView subclass add nib subview

I have a custom UIView subclass let's call it CustomViewA which I init with initWithFrame: and add some UIViews programatically (like a UILabel and so on). Now there is need for another view to be added to CustomViewA so I created a nib which I lay out some GUI elements inside (one being a UISegmentedControl)

Now I'm having some issues on how to correctly add this nib as a subview to CustomViewA. Do I need to create .h/.m files for the nib? I want CustomViewA to receive the actions when the segmented control changes values.

Upvotes: 0

Views: 896

Answers (3)

Peter Warbo
Peter Warbo

Reputation: 11700

I finally figured out what was happening. The nib that I added to CustomViewA was added outside CustomViewAs frame. So apparently when a subview is outside the superview's frame it will not intercept touches.

Upvotes: 0

KudoCC
KudoCC

Reputation: 6952

Do I need to create .h/.m files for the nib?

No, you needn't.

How to receive the actions when the segmented control changes values ?

You can set a tag number for segmented control in your xib, it should be unique in all the subviews of the view in your xib.

You can get the segmented control with the code. UISegmentedControl *segmentedControl = (UISegmentedControl *)[view viewWithTag:1024];, once you get the segmented control, you can add an action with the code [segmentedControl addTarget:self action:@selector(action:) forControlEvents:UIControlEventValueChanged];

Edit: How to get the root view of xib?

Use the code below:

UIView *rootView = [[[NSBundle mainBundle] loadNibNamed:@"YourXibName" owner:nil options:nil] firstObject];

Upvotes: 1

jaggedcow
jaggedcow

Reputation: 1405

[[NSBundle mainBundle] loadNibNamed:@"MyNibName" owner:self options:nil];
[self.view addSubview:self.nibView];

In the nib, make sure that the File Owner's class is set to the view controller you are adding it to.

You can add properties and IBActions like normal from the nib as well.

Upvotes: 1

Related Questions