为什么self.navigationItem.titleView有时候不能居中呢
答一
:UINavigationBar
automatically centers its titleView
as long as there is enough room. If the title isn't centered that means that the title view is too wide to be centered, and if you set the backgroundColor if your UIImageView
you'll see that's exactly what is happening.
The title view is too wide because that navigation bar will automatically resize the title to hold its content, using -sizeThatFits:
. This means that your title view will always be resized to the size of your image.
怎么让它居中呢
值得注意的是如果你的titleView是Label什么的 TextAlignment应该设成center 使用sizetofit
答一
It's possible to start with the titleView being the screen width, then after the navigation bar changes titleView.frame, update it again yourself in the view controller's viewDidAppear:. Using its adjusted titleView.frame.origin.x and size.width along with the screen width, you can calculate the largest of the left & right margins, then set the origin.x to that, the size.width to the screen width minus that times 2. However that doesn't take effect until after the pushed view has animated in and the shift afterwards is visible. You could hide the titleView in viewWillAppear: then unhide in viewDidAppear: after centering it, so instead of sliding in with an off-center titleView which is then shifted, it would slide in with no title which then appears.
A better possibility is to make your titleView your own subclass of UIView (or UILabel or whichever) and override setFrame to resize itself to stay centered in its superview. If I ever end up doing this myself I'll post it here. Or maybe someone else knows another place to change the titleView's frame after its been updated but before the view slides in without a view subclass.
这种方法我自己亲测可用 CustomView中重写setframe方法 self.navigationItem.titleView = customView
- (void)setFrame:(CGRect)frame
{
[super setFrame:frame];
self.center = CGPointMake(self.superview.center.x, self.center.y);
}
答二:Just add your image to navigationController.navigationBar
CGRect myImageS = CGRectMake(0, 0, 44, 44);
UIImageView *logo = [[UIImageView alloc] initWithFrame:myImageS];
[logo setImage:[UIImage imageNamed:@"color.png"]];
logo.contentMode = UIViewContentModeScaleAspectFit;
logo.center = CGPointMake(self.navigationController.navigationBar.width / 2.0, self.navigationController.navigationBar.height / 2.0);
logo.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
[self.navigationController.navigationBar addSubview:logo];