如何修改我的UILabel子类以便它可以接受自定义值?

时间:2017-12-05 06:21:47

标签: ios swift

这是我目前的课程。

class PaddedUILabel: UILabel {
    var padding = UIEdgeInsets(top: 4, left: 8, bottom: 4, right: 8)


    override func drawText(in rect: CGRect) {
        super.drawText(in: UIEdgeInsetsInsetRect(rect, padding))
    }

    // Override -intrinsicContentSize: for Auto layout code
    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 -sizeThatFits: for Springs & Struts code
    override func sizeThatFits(_ size: CGSize) -> CGSize {
        let superSizeThatFits = super.sizeThatFits(size)
        let width = superSizeThatFits.width + padding.left + padding.right
        let heigth = superSizeThatFits.height + padding.top + padding.bottom
        return CGSize(width: width, height: heigth)
    }
}

现在,填充码是硬编码的。我希望能够在StoryBoard UI(顶部,左侧,底部,右侧)中设置自定义值。

我可以对我的代码做些什么来修改它?

1 个答案:

答案 0 :(得分:0)

import Foundation

@IBDesignable class UILabelExtendedView: UILabel {
@IBInspectable var topInset: CGFloat = 4.0
@IBInspectable var bottomInset: CGFloat = 4.0
@IBInspectable var leftInset: CGFloat = 8.0
@IBInspectable var rightInset: CGFloat = 8.0

override func drawText(in rect: CGRect) {
    let insets: UIEdgeInsets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
    super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}

override public var intrinsicContentSize: CGSize {
    var contentSize = super.intrinsicContentSize
    contentSize.height += topInset + bottomInset
    contentSize.width += leftInset + rightInset
    return contentSize
}

func setPadding(top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat) {
    self.topInset = top
    self.bottomInset = bottom
    self.leftInset = left
    self.rightInset = right
    let insets: UIEdgeInsets = UIEdgeInsets(top: top, left: left, bottom: bottom, right: right)
    super.drawText(in: UIEdgeInsetsInsetRect(self.frame, insets))
}}

将此类名称传递给storyboard中的标签,然后在属性检查器中设置您的填充。

相关问题