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

故事扮演 提交于 2019-12-22 05:00:32

问题


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?


回答1:


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.




回答2:


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




回答3:


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
        }
    }


来源:https://stackoverflow.com/questions/12112657/xcode-is-there-a-way-to-change-line-spacing-ui-label-in-interface-builder

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