-->

How to create a UINavigationItem.TitleView based u

2019-04-16 06:01发布

问题:

I have a UINavigationController bassed sequence of screens. On one of the screens I want to replace the standard title with a custom TitleView. The custom view will be created with a nib file and will have an image and several labels.

Do I create a UIViewController w/ associated nib file, load the nib, and assign the .view property to the TitleView? Basically, how do I use a nib where I can layout the necessary elements and then assign the resulting view to the TitleView property?

回答1:

Consider using UINib - it was exposed in iOS 4.0. It double perf since it caches the nib for you.

UINib *nib = [UINib nibWithNibName:@"TestView" bundle:nil];
UIView *myView = [[nib instantiateWithOwner:self options:nil] objectAtIndex:0]];

The objectAtIndex refers to the top level views in the NIB - typically there's one (index 0) but if there's many, you need to provide the index.

Once you have the view you can assign it to the navigationItem titleView

self.navigationItem.titleView = myView;
[myview release];

EDIT:

If you need to get to the individual controls within the NIB, puts tags on them and access them via viewWithTag. See here:

http://useyourloaf.com/blog/2011/2/28/speeding-up-table-view-cell-loading-with-uinib.html



回答2:

Create your custom view in Interface Builder & load it to a view(or you can create an IBOutlet iVar to point the view). Then just set the titleView to your custom view.

UIView * customTitleView = [[[NSBundle mainBundle] loadNibNamed:@"TitleView" owner:self options:nil] lastObject];
self.navigationItem.titleView = customTitleView;
[customTitleView release];