Xcode:有没有办法在界面构建器中更改行间距(UI标签)?

时间:2012-08-24 15:48:04

标签: xcode cocoa-touch interface-builder uilabel

我有几个带有多行文字的UILabel,但行间距比我想要的要大。有没有办法改变这个?

3 个答案:

答案 0 :(得分:37)

嗨,这是一个迟到的回复,但它可以帮助某些行高度可以更改文本从普通文件更改为属性enter image description here

答案 1 :(得分:2)

自iOS 6起,Apple将NSAttributedString添加到UIKit,从而可以使用NSParagraphStyle更改行间距。

要从NIB实际更改please see souvickcse's answer.

答案 2 :(得分:0)

因为我讨厌在界面生成器中使用属性文本(我总是会遇到IB错误),所以此扩展允许您直接在界面生成器中将行高设置为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
        }
    }