Can't set titleView in the center of navigation bar because back button

前端 未结 10 1542
情话喂你
情话喂你 2020-12-08 02:25

I\'m using an image view to display an image in my nav bar. The problem is that I can\'t set it to the center correctly because of the back button. I checked the related que

10条回答
  •  南方客
    南方客 (楼主)
    2020-12-08 03:05

    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.

    Two possible fixes:

    1. The image you're using is way too big. Use a properly sized 44x44 pt image with 2x and 3x versions.

    2. Wrap UIImageView inside of a regular UIView to avoid resizing.

    Example:

    UIImageView* imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"test.jpeg"]];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    
    UIView* titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    imageView.frame = titleView.bounds;
    [titleView addSubview:imageView];
    
    self.navigationItem.titleView = titleView;
    

提交回复
热议问题