Core Text - NSAttributedString line height done right?

前端 未结 10 918
Happy的楠姐
Happy的楠姐 2020-12-23 09:21

I\'m completely in the dark with Core Text\'s line spacing. I\'m using NSAttributedString and I specify the following attributes on it: - kCTFontAttributeName - kCTParagraph

10条回答
  •  鱼传尺愫
    2020-12-23 09:36

    Swift 4 & 5

    extension NSAttributedString {
    
        /// Returns a new instance of NSAttributedString with same contents and attributes with line spacing added.
         /// - Parameter spacing: value for spacing you want to assign to the text.
         /// - Returns: a new instance of NSAttributedString with given line spacing.
         func withLineSpacing(_ spacing: CGFloat) -> NSAttributedString {
             let attributedString = NSMutableAttributedString(attributedString: self)
             let paragraphStyle = NSMutableParagraphStyle()
             paragraphStyle.lineBreakMode = .byTruncatingTail
             paragraphStyle.lineSpacing = spacing
             attributedString.addAttribute(.paragraphStyle,
                                           value: paragraphStyle,
                                           range: NSRange(location: 0, length: string.count))
             return NSAttributedString(attributedString: attributedString)
         }
    }
    

提交回复
热议问题