Xcode中:有没有办法在Interface Builder中改变行距(UI标签)?(Xcode:

2019-07-31 03:42发布

我有几个UILabels与多行文本,但行距大于我宁愿。 有什么办法来改变这种?

Answer 1:

由于iOS 6中,苹果加入NSAttributedStringUIKit ,使得有可能使用NSParagraphStyle改变行距。

要真正从NIB更改, 请参阅souvickcse的答案。



Answer 2:

你好,这是一个迟到的答复,但它可以帮助一些一行高度可以改变而改变,从纯文本属性



Answer 3:

因为我使用界面生成器属性文本(我一直运行到IB的bug)受诅咒的仇恨,这里是一个扩展,让您可以直接设置行高多至一个UILabel在界面生成器

extension UILabel {

    @IBInspectable
    var lineHeightMultiple: CGFloat {
        set{

            //get our existing style or make a new one
            let paragraphStyle: NSMutableParagraphStyle
            if let existingStyle = attributedText?.attribute(NSAttributedString.Key.paragraphStyle, at: 0, effectiveRange: .none) as? NSParagraphStyle, let mutableCopy = existingStyle.mutableCopy() as? NSMutableParagraphStyle  {
                paragraphStyle = mutableCopy
            } else {
                paragraphStyle = NSMutableParagraphStyle()
                paragraphStyle.lineSpacing = 1.0
                paragraphStyle.alignment = self.textAlignment
            }
            paragraphStyle.lineHeightMultiple = newValue

            //set our text from existing text
            let attrString = NSMutableAttributedString()
            if let text = self.text {
                attrString.append( NSMutableAttributedString(string: text))
                attrString.addAttribute(NSAttributedString.Key.font, value: self.font, range: NSMakeRange(0, attrString.length))
            }
            else if let attributedText = self.attributedText {
                attrString.append( attributedText)
            }

            //add our attributes and set the new text
            attrString.addAttribute(NSAttributedString.Key.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
            self.attributedText = attrString
        }

        get {
            if let paragraphStyle = attributedText?.attribute(NSAttributedString.Key.paragraphStyle, at: 0, effectiveRange: .none) as? NSParagraphStyle {
                return paragraphStyle.lineHeightMultiple
            }
            return 0
        }
    }


文章来源: Xcode: Is there a way to change line spacing (UI Label) in interface builder?