英文:
using baselineOffset in NSAttributedString problem in iOS 16.4
问题
I see, after building the project on iOS 16.4, you encountered an issue with the baselineOffset
that differs from iOS 16.0.
这是我的代码:
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
}
}
英文:
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?
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
}
}
答案1
得分: 3
确实,在iOS 16.4中,baselineOffset
的工作方式发生了变化。
看起来苹果修复了UILabel
的旧 bug。早先,UILabel
的 baselineOffset
值需要翻倍,原因不明。而对于 UITextView
,baselineOffset
的工作正常,无需翻倍。
如果您希望在iOS的两个版本上实现相同的行为,您可以尝试将以下代码进行替换:
let baselineOffset = 20
替换为:
let baselineOffset: CGFloat = {
if #available(iOS 16.4, *) {
return 40
} else {
return 20
}
}()
英文:
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:
<!-- language: swift -->
let baselineOffset = 20
to
<!-- language: swift -->
let baselineOffset: CGFloat = {
if #available(iOS 16.4, *) {
return 40
} else {
return 20
}
}()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论