iOS 如何制做内边距UILabel

前言:

常常在某 App 上看到文字 Label 带有圆角边框之类的, 若是直接设置 Label 的layer 圆角属性, 会发现圆角太靠近文字了,黏在一块儿很差看,我之前的作法是, 弄一个 UIView, 上面放个 UILabel, 这个办法其实很辣鸡. 我从没有使用过这种方法.
今天看到了一个不错的方法, 这里记录一下.ide

效果图code


1235875-7fce97b53e4c4237.png
1.png
1235875-36fa0b5339e313b1.png
2.png

代码blog

import UIKit

class YXPaddingLabel: UILabel {

    var circularFillet = false

    let padding = UIEdgeInsets(top: 3, left: 8, bottom: 3, right: 8)
    override func drawText(in rect: CGRect) {
        super.drawText(in: UIEdgeInsetsInsetRect(rect, padding))
    }

    override var intrinsicContentSize : CGSize {
        let superContentSize = super.intrinsicContentSize
        let width = superContentSize.width + padding.left + padding.right
        let heigth = superContentSize.height + padding.top + padding.bottom
        return CGSize(width: width, height: heigth)
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        if circularFillet == true {
            let h = self.layer.frame.size.height
            self.layer.cornerRadius = h / 2
        }
    }
}

图片中的示例代码图片

labelOriginal.layer.borderColor = UIColor.red.cgColor
    labelOriginal.layer.borderWidth = 1
    labelOriginal.font = UIFont.systemFont(ofSize: 20)
    
    label1.layer.borderColor = UIColor.red.cgColor
    label1.layer.borderWidth = 1
    label1.font = UIFont.systemFont(ofSize: 20)
    
    label2.layer.cornerRadius = 10
    label2.layer.borderColor = UIColor.red.cgColor
    label2.layer.borderWidth = 1
    label2.font = UIFont.systemFont(ofSize: 20)
    
    label3.layer.borderColor = UIColor.red.cgColor
    label3.layer.borderWidth = 1
    label3.font = UIFont.systemFont(ofSize: 20)
    label3.circularFillet = true
    
    let label4 = YXPaddingLabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
    label4.center = view.center
    label4.textAlignment = .center
    label4.textColor = UIColor.purple
    label4.text = "自定义控件4"
    label4.layer.cornerRadius = 25
    label4.layer.backgroundColor = UIColor.yellow.cgColor
    label4.layer.borderColor = UIColor.red.cgColor
    label4.layer.borderWidth = 1
    label4.font = UIFont.systemFont(ofSize: 20)
    view.addSubview(label4)