0

I am having an issue with this function:

    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.gray
    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.black
    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

}

// Use : self.navigationItem.titleView = setTitle("title", "subtitle")

// Source : http://stackoverflow.com/questions/12914004/uinavigationbar-titleview-with-subtitle

English text

Arabic text

as shown above images, whenever someone writes in arabic[picture 2] the title will be messed up, but if someone wrote it in English[picture 1]. the label of title will remain good.

thank you in advance.

Antony Raphel
  • 2,036
  • 2
  • 25
  • 45
Kamel
  • 41
  • 7

1 Answers1

1

I ran code with all combinations of arabic and english words and found the problem in code. Check it out.

    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 /* subtitleLabel.frame = frame.integral */
    }
Navneet Gill
  • 393
  • 1
  • 13