如何在 IOS 中制作带圆角边框的填充 UILabel

How can I make a padded UILabel with rounded border in IOS

我在这里找到了构建填充标签的解决方案 and saw an answer that uses IBInspectable to make it simple to use from InterfaceBuilder here: 。我也想有相同的 class 提供在一个包中指定边框(宽度、颜色和圆角半径)的能力。

我正在此处构建用于在此处找到的填充标签的解决方案: and also the use of IBInspectable found here: , and finally the border stuff from here: 请注意,背景颜色仍然可以按照您已经可以在 Interface Builder 中为标签设置的常规方式设置

    import UIKit

    @IBDesignable class PaddedAndBorderedLabel: UILabel {

        @IBInspectable var topInset: CGFloat = 5.0
        @IBInspectable var bottomInset: CGFloat = 5.0
        @IBInspectable var leftInset: CGFloat = 7.0
        @IBInspectable var rightInset: CGFloat = 7.0
        @IBInspectable var borderColor : UIColor = UIColor.black
        @IBInspectable var borderWidth : CGFloat = 1
        @IBInspectable var cornerRadius : CGFloat = 5
        
        override func drawText(in rect: CGRect) {
            let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
            super.drawText(in: rect.inset(by: insets))
        }


        override var intrinsicContentSize: CGSize {
            let size = super.intrinsicContentSize
            return CGSize(width: size.width + leftInset + rightInset,
                  height: size.height + topInset + bottomInset)
        }

        override func textRect(forBounds bounds:CGRect,
                           limitedToNumberOfLines n:Int) -> CGRect {
            let b = bounds
            let UIEI = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
            let tr = b.inset(by: UIEI)
            let ctr = super.textRect(forBounds: tr, limitedToNumberOfLines: 0)
            // that line of code MUST be LAST in this function, NOT first
            return ctr
        }            

        override func draw(_ rect: CGRect) {
            layer.borderColor = borderColor.cgColor
            layer.borderWidth = borderWidth
            layer.cornerRadius = cornerRadius
            layer.masksToBounds = true
            super.draw(rect)
        }
    }