How to create a UINavigationItem.TitleView based u

2019-04-16 06:13发布

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?

2条回答
神经病院院长
2楼-- · 2019-04-16 06:27

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

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-04-16 06:33

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];
查看更多
登录 后发表回答