思い立ったが吉日!

iOSが好きです。

UILabelに行間をつける

上下余白のLabelと行間をつけるLabel

iOSアプリでヒラギノ角ゴを使っているとUILael に上下余白を付けないとjやgの下が切れちゃいますね。

(ちなみにベトナム語とかに対応する場合は、上にも長いので上下に余白つけると良いですね)

なのでよく上下paddingのラベルはUtilとして用意することはあると思います。

上下paddingのラベル

/*
 行間のないただのヒラギノ角ゴ対策用の上下padding label
 */

class NoLineSpacePaddingLabel: UILabel {

    // paddingの値
    let padding = UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2)
    override func drawTextInRect(rect: CGRect) {
        let newRect = UIEdgeInsetsInsetRect(rect, padding)
        super.drawTextInRect(newRect)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        //        numberOfLines = customNumberOfLines
    }
    
    override func intrinsicContentSize() -> CGSize {
        var intrinsicContentSize = super.intrinsicContentSize()
        intrinsicContentSize.height += padding.top + padding.bottom
        intrinsicContentSize.width += padding.left + padding.right
        return intrinsicContentSize
    }
}

しかし、これが複数行になった場合、一番上と一番下にしか余白が付きません。

この場合、frameの上下に余白をつけるより、行そのものに余白を付けるやり方のほうが良さそうです。

行間に余白を付けるLabel

@IBDesignable
class PaddingLabel: UILabel {
 @IBInspectable var customNumberOfLines: Int = 0
    
    override var text: String? {
        didSet {
            if let text = text {
                let paragraphStyle = NSMutableParagraphStyle()
                paragraphStyle.alignment = self.textAlignment
                paragraphStyle.lineBreakMode = self.lineBreakMode
                // fontサイズとって行の高さに余白つけないと上下中央にならない
                paragraphStyle.minimumLineHeight = self.font.pointSize + 6
                paragraphStyle.maximumLineHeight = self.font.pointSize + 6
                let attributedText = NSMutableAttributedString(string: text)
                attributedText.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSRange(location: 0, length: attributedText.length))
                self.attributedText = attributedText
            }
            layoutIfNeeded()
        }
    }
 
    
    override func layoutSubviews() {
        super.layoutSubviews()
        numberOfLines = customNumberOfLines
    }

}