1

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?

E.g. 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?

Community
  • 1
  • 1
Gavin Hope
  • 2,173
  • 24
  • 38

2 Answers2

1

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.

Red Nightingale
  • 669
  • 3
  • 19
0

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.

Rikkles
  • 3,372
  • 1
  • 18
  • 24
  • Thx. I had two reasons: (1) the automatic change to the height of the view, e.g. from portrait to landscape. I'm adding a single tap gesture recognizer to that `UILabel`... in practice setting the height to 32 rather than 44 isn't a problem. (2) updates to the back button... Navigation Controller removes hides/shows the back button text depending on size of the title. Using the code above, it doesn't respond in the same way as if I just set `UINavigationItem.title`. I wondered if using auto layout was more correct, and would lead to correct interaction with the back button... – Gavin Hope Aug 26 '14 at 12:31
  • My experience is that you need to do a lot more to mimic the standard title, especially if you just want to modify a single aspect of it. – Rikkles Aug 26 '14 at 13:56
  • a lot more, for example setting the frame or constraints... and, interacting with the other `UINavigationItem` objects? Or other stuff? Cheers. – Gavin Hope Aug 26 '14 at 17:34
  • 2
    For handling the frame sizes, rotation, mostly – Rikkles Aug 26 '14 at 17:47