Custom Title View not Centered in iOS 10

2019-07-20 14:52发布

This post is a separate topic but related to Custom Nav Title offset ios 11

I created a new thread because it is a separate issue.

enter image description here

From project: https://github.com/ekscrypto/Swift-Tutorial-Custom-Title-View

To recreate the problem, simply put a button on the existing Root View Controller that pushes another view controller. The "< Back" button scoots the title over, which makes it terribly uncentered. How can I fix this? Thank you.

2条回答
该账号已被封号
2楼-- · 2019-07-20 15:35

Simple change required to support earlier versions of iOS; you should properly resize your custom title view to be the expected width its actually going to be. iOS 11 attempts to resize the width of the title view to fit the available space based on the constraints but iOS 10 and below will try to maintain the size of the view as much as possible.

The solution is therefore to open the MyCustomTitleView.xib file, and to set the width of the MyCustomTitleView to something reasonable like 180pt.

Cheers!

查看更多
干净又极端
3楼-- · 2019-07-20 15:51

For iOS 10 and below you need to set up CGFrame for your attributed titleLabel. Here is the code example.

- (void)viewDidLoad {
    [super viewDidLoad];

    UILabel *titleLabel = [[UILabel alloc]init];
    NSDictionary *fontAttribute = @{ NSFontAttributeName:[UIFont fontWithName:@"SFProText-Medium" size:15.f]};
    NSAttributedString *str = [[NSAttributedString alloc]initWithString:@"YOUR TITLE"
    attributes:fontAttribute];
    titleLabel.attributedText = str;
    [titleLabel sizeToFit]; // This method create a frame
    self.navigationItem.titleView = titleLabel;

}

Swift example:

override func viewDidLoad() {
    super.viewDidLoad()

    let titleLabel = UILabel()
    let title = NSMutableAttributedString(string: "Your title", attributes:[
        NSAttributedStringKey.foregroundColor: UIColor.blue,
        NSAttributedStringKey.font: UIFont.systemFont(ofSize: 17.0, weight: UIFont.Weight.light)])
    titleLabel.attributedText = title
    titleLabel.sizeToFit()
    self.navigationItem.titleView = titleLabel

}
查看更多
登录 后发表回答