UINavigationItem centering the title

前端 未结 7 526
深忆病人
深忆病人 2020-12-23 22:01

I have a navigationBar with both Left and Right bar buttons on each side. I have a customTitlelabel which I set as the titleView of the UINavigationItem

7条回答
  •  轮回少年
    2020-12-23 22:48

    Setting the titleView property of the nav bar works just fine - no need to subclass or alter any frames other than those of your custom view.

    The trick to getting it centered relative to the overall width of UINavigationBar is to:

    1. set the width of your view according to the size of the text
    2. set the alignment to centered and
    3. set the autoresizingmask so it gets resized to the available space

    Here's some example code that creates a custom titleView with a label which remains centred in UINavigationBar irrespective of orientation, left or right barbutton width:

    self.title = @"My Centered Nav Title";
    
    // Init views with rects with height and y pos
    CGFloat titleHeight = self.navigationController.navigationBar.frame.size.height;
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectZero];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    
    // Set font for sizing width
    titleLabel.font = [UIFont boldSystemFontOfSize:20.f];
    
    // Set the width of the views according to the text size
    CGFloat desiredWidth = [self.title sizeWithFont:titleLabel.font
                                constrainedToSize:CGSizeMake([[UIScreen mainScreen] applicationFrame].size.width, titleLabel.frame.size.height)
                                    lineBreakMode:UILineBreakModeCharacterWrap].width;
    
    CGRect frame;
    
    frame = titleLabel.frame;
    frame.size.height = titleHeight;
    frame.size.width = desiredWidth;
    titleLabel.frame = frame;
    
    frame = titleView.frame;
    frame.size.height = titleHeight;
    frame.size.width = desiredWidth;
    titleView.frame = frame;
    
    // Ensure text is on one line, centered and truncates if the bounds are restricted
    titleLabel.numberOfLines = 1;
    titleLabel.lineBreakMode = UILineBreakModeTailTruncation;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    
    // Use autoresizing to restrict the bounds to the area that the titleview allows
    titleView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    titleView.autoresizesSubviews = YES;
    titleLabel.autoresizingMask = titleView.autoresizingMask;
    
    // Set the text
    titleLabel.text = self.title;
    
    // Add as the nav bar's titleview
    [titleView addSubview:titleLabel];
    self.navigationItem.titleView = titleView;
    

提交回复
热议问题