简体   繁体   中英

Setting UINavigationItem's titleView: setFrame vs. Auto Layout Constraints

I'm switching over to use auto layout, programatically, so it's all new to me. As a general rule, I think I should be avoiding setting any frames directly...

Problem: I want to use a UILabel as the view for my view controller's UINavigationItem titleView .

Is it possible to use auto layout constraints with the navigation bar / navigation item? Or, do we still need to set the frame directly in some circumstances?

Eg I'm doing something like this:

UILabel* title = [UILabel new];
title.text = @"Some Title";
[title sizeToFit];
CGFloat titleWidth = title.bounds.size.width;
[title setFrame:CGRectMake(0, 0, titleWidth, 32.0)];
self.navigationItem.titleView = title;

As you can see, I've set the height of that view to 32.0 (for landscape mode). Further, I allow the title text to change, so I re-do the sizeToFit and setFrame if the user makes a change.

Is this the way to do it? Or, is there an auto layout way?

Note: I have looked at this question/answer: Building a titleView programmatically with constraints (or generally constructing a view with constraints)

Reading through that - I'm still not sure if it's possible to use constraints only ?

One more trick... The view you set as navigationItem.titleView MUST NOT HAVE translatesAutoresizingMaskIntoConstraints = false or it will fly all over the navbar during navigation animations. You'll also need to make sure you set the frame width and height.

I believe that you can. But why would you? Anyway, the constraints need to be:

  • Top margin to superview
  • Height

From the docs, the titleView is centered in the navigation frame, and resizes to fit. So technically you don't need anything other than the above, but you might have to also specify the left margin to superview.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM