How to resize Title in a navigation bar dynamically

前端 未结 9 1941
慢半拍i
慢半拍i 2020-12-03 01:24

I have some views that show up in a navigation controller. Two of these views have a longer title for the navigation bar.

The problem is that when the title is too

9条回答
  •  难免孤独
    2020-12-03 02:05

    Swift 4 and iOS 13

    Adding this so my future self can find it. Views added to titleView for some reason don't like to automatically resize themselves. So you have to do it manually.

    Example

    (navigationItem.titleView as? UILabel)?.text = "A longer string..." // label not resized and text is cut off
    

    Solution

    navigationItem.titleView?.translatesAutoresizingMaskIntoConstraints = false
    navigationItem.titleView?.setNeedsLayout()
    navigationItem.titleView?.layoutIfNeeded()
    navigationItem.titleView?.translatesAutoresizingMaskIntoConstraints = true
    

    Thanks to @Paolo Musolino for leading me here.

提交回复
热议问题