Xcode: Is there a way to change line spacing (UI L

2020-08-26 10:36发布

I've got several UILabels with multiple lines of text, but the line spacing is larger than I would prefer. Is there any way to change this?

3条回答
干净又极端
2楼-- · 2020-08-26 11:22

Since iOS 6, Apple added NSAttributedString to UIKit, making it possible to use NSParagraphStyle to change the line spacing.

To actually change it from NIB, please see souvickcse's answer.

查看更多
forever°为你锁心
3楼-- · 2020-08-26 11:31

hi this is a late reply but it may help some one line height can be change change the text from plain to attribute enter image description here

查看更多
孤傲高冷的网名
4楼-- · 2020-08-26 11:33

Because I friggin hate using attributed text in interface builder (I always run into IB bugs), here is an extension to allow you to set line height multiple directly to a UILabel in interface builder

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
        }
    }
查看更多
登录 后发表回答