Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using baselineOffset in NSAttributedString problem in iOS 16.4

as you can see, after i build project on iOS 16.4 i faced a problem that baselineOffset is not like on iOS 16.0.

what should i do?

enter image description here

this is my code:

class ViewController: UIViewController {
    @IBOutlet weak var label: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        self.label.setText("Hello World!")
    }


}


extension UILabel {
    func setText(_ text: String) {
        let attrs = self.generateFontAttr()
        self.attributedText = NSAttributedString(string: text, attributes: attrs)
    }

    private func generateFontAttr() -> [NSAttributedString.Key: Any] {
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.maximumLineHeight = 120
        paragraphStyle.minimumLineHeight = 120
        let font = UIFont.systemFont(ofSize: 18)
        let baselineOffset = 20
        let attrs: [NSAttributedString.Key: Any] = [
            .font: font,
            .paragraphStyle: paragraphStyle,
            .baselineOffset: baselineOffset
        ]

        return attrs
    }

}

like image 751
Sajjad Avatar asked Oct 27 '25 22:10

Sajjad


1 Answers

Indeed there has been a change in how baselineOffset works in iOS 16.4.

It looks like Apple fixed an old bug with UILabel baselineOffset. Earlier the baselineOffset value had to be doubled for unknown reasons. For UITextView baselineOffset worked fine without doubling.

what should i do?

Your question is not precise but if you would like to achieve the same behavior on both versions of iOS, you can try to replace:

let baselineOffset = 20

to

let baselineOffset: CGFloat = {
    if #available(iOS 16.4, *) {
        return 40
    } else {
        return 20
    }
}()
like image 137
Łukasz Gierałtowski Avatar answered Oct 30 '25 15:10

Łukasz Gierałtowski