lineSpacing property inside UILabel doesn't work as expected

守給你的承諾、 提交于 2019-12-12 00:33:12

问题


I am trying to create a custom UILabel class which will allow me to increase the line spacing on a UILabel. I know you can do this in IB with an attributed text string, however it doesn't work if you are using custom fonts. Here is my class code:

import UIKit

@IBDesignable
class SpacingLabel: UILabel
{

    @IBInspectable var lineSpacing: CGFloat = 10.0

    override func awakeFromNib()
    {
        self.renderText()
    }

    override func prepareForInterfaceBuilder()
    {
        super.prepareForInterfaceBuilder()
        self.renderText()
    }

    func renderText()
    {
        var attrString = NSMutableAttributedString(string:self.text!)

       if font != nil
        {
            NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy()
            var paragraphStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as!     NSMutableParagraphStyle 
            paragraphStyle.textAlignment = self.textAlignment

            paragraphStyle.lineSpacing = self.lineSpacing
            paragraphStyle.paragraphSpacing = self.lineSpacing

            attrString.addAttributes([NSFontAttributeName : self.font!, NSParagraphStyleAttributeName : paragraphStyle], range: NSMakeRange(0, attrString.length))
            self.attributedText = attrString
        }

        self.needsUpdateConstraints()
    }

}

This is how it renders in IB (Storyboard):

And here's how it renders in the simulator:

I've tried adding minimumLineHeight and/or maximumLineHeight properties, but these just seem to mess it up in other ways...


回答1:


So... It turned out that the property lineSpacing is somehow clashing with a possible private variable/property within UILabel. I renamed my property to leading and now it works perfectly.



来源:https://stackoverflow.com/questions/32008465/linespacing-property-inside-uilabel-doesnt-work-as-expected

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