简体   繁体   English

UILabel中的lineSpacing属性无法按预期工作

[英]lineSpacing property inside UILabel doesn't work as expected

I am trying to create a custom UILabel class which will allow me to increase the line spacing on a UILabel. 我正在尝试创建一个自定义UILabel类,这将允许我增加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. 我知道您可以在IB中使用带有属性的文本字符串来执行此操作,但是如果您使用自定义字体,则无法使用。 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): 这是它在IB(故事板)中的呈现方式:

在此处输入图片说明

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... 我尝试添加minimumLineHeight和/或maximumLineHeight属性,但是这些似乎以其他方式将其弄乱了……

So... It turned out that the property lineSpacing is somehow clashing with a possible private variable/property within UILabel . 所以...事实证明,属性lineSpacingUILabel可能的私有变量/属性发生了冲突。 I renamed my property to leading and now it works perfectly. 我将自己的媒体资源重命名为leading ,现在可以正常使用了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM