Home>

Developed without a storyboard.

What i am doing

NavigationItem.titleView can be displayed using the following code.
Transition from view A displaying this to another view B,
So change the text of navigationItem.titleView.

Don't know

When you return to view A after the change,
The y position of titleLabel and subtitleLabel is the same position and will overlap.

Ask me a question because I don't know why.
Thank you.

func setTitle (title: String, subtitle: String)->UIView {

        let titleLabel = UILabel (frame: CGRect (x: 0, y: -5, width: 0, height: 0))
        titleLabel.backgroundColor = UIColor.clear
        titleLabel.textColor = UIColor.black
        titleLabel.font = UIFont.boldSystemFont (ofSize: 17)
        titleLabel.text = title
        titleLabel.sizeToFit ()


        let subtitleLabel = UILabel (frame: CGRect (x: 0, y: 18, width: 0, height: 0))
        subtitleLabel.backgroundColor = UIColor.clear
        subtitleLabel.textColor = UIColor.gray
        subtitleLabel.font = UIFont.systemFont (ofSize: 12)
        subtitleLabel.text = subtitle
        subtitleLabel.sizeToFit ()

        let titleView = UIView (frame: CGRect (x: 0, y: 0, width: max (titleLabel.frame.size.width, subtitleLabel.frame.size.width), height: 30))
        titleView.addSubview (titleLabel)
        titleView.addSubview (subtitleLabel)
        let widthDiff = subtitleLabel.frame.size.width-titleLabel.frame.size.width
        if widthDiff>0 {
            var frame = titleLabel.frame
            frame.origin.x = widthDiff/2
            titleLabel.frame = frame.integral
        } else {
            var frame = subtitleLabel.frame
            frame.origin.x = abs (widthDiff)/2
            titleLabel.frame = frame.integral
        }
        return titleView
    }
  • Answer # 1

    We confirmed that the display differs depending on text.count (number of characters).
    If the number of characters is 10 or more, it will be displayed correctly, and if it is less than that, it will be displayed overlapping.

    My personal settings were a problem. Sorry for the lack of confirmation.