UITextView lineHeightMultiple Clips Top, first line, of Text

房东的猫 提交于 2019-12-05 19:45:48

I had the same issue.

I compensated it using NSBaselineOffsetAttributeName.

You should use:

let attributes = [
    NSParagraphStyleAttributeName: paragraph,
    NSFontAttributeName: font,
    NSBaselineOffsetAttributeName: -5
]

You will have to also set a lower paragraph.lineHeightMultiple.

A little tricky, but it works.

Cooliopas is right, but I ended up using this in a label extension and needed something more suited for the many different sizes of text throughout my app. I found that the baseline adjustment to keep the text vertically centered was 10% of the height of the text.

let attrString = NSMutableAttributedString(string: newText)

let style = NSMutableParagraphStyle()
style.alignment = self.textAlignment
style.lineSpacing = 1.0
style.lineHeightMultiple = 0.75

var baselineOffset : CGFloat = -5 //-5 is a default for this in case there is no attributedText size to reference
if let size = self.attributedText?.size(){
  baselineOffset = size.height * -0.1
} else {
  NSLog("attributedText = nil, setting lineHeightMultiple to -5 as a default for ", newText)
}

attrString.addAttribute(NSParagraphStyleAttributeName, value: style, range: NSMakeRange(0, attrString.length))
attrString.addAttribute(NSBaselineOffsetAttributeName, value: baselineOffset, range: NSMakeRange(0, attrString.length))
self.clipsToBounds = false

self.attributedText = attrString
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!