0

I have a navigationBar with rightButtonItem and another navigationBar with right&leftButtonItem.
I practice to try navigationBar with subTitle, but when I set title&subtitle string to be long.
It will be overlapping, and the string is truncating.
What do I fix this issue?

Issue picture_1
Issue picture_2

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.red
    titleLabel.font = UIFont.boldSystemFont(ofSize: 14)
    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.blue
    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

}//source from here:https://gist.github.com/nazywamsiepawel/0166e8a71d74e96c7898
JimmyLee
  • 507
  • 2
  • 7
  • 24

2 Answers2

0

Instead of creating another label, you can try one label with two lines so that they won't overlap. Use this code

label.numberOfLines = 2

When you set text, use \n in your string to indicate next line, like this

label.text= "Main title\nSub title"

If you want different font for the two titles, try to use attributed string like this

Fangming
  • 24,551
  • 6
  • 100
  • 90
0

One little edit needed in this section of your code:

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

    // this should be *subtitleLabel*
    //titleLabel.frame = frame.integral
    subtitleLabel.frame = frame.integral

}
DonMag
  • 69,424
  • 5
  • 50
  • 86