0

This is how looks my subclass for UILabel:

@IBDesignable class AttributedLabel: UILabel {

    @IBInspectable var padding: CGFloat = 0

    override func drawTextInRect(rect: CGRect) {
        super.drawTextInRect(UIEdgeInsetsInsetRect(rect, UIEdgeInsetsMake(padding, padding, padding, padding)))
    } 
}

I correctly set padding in storyboard but It doesnt work because padding is still 0.

What to do to make it working? Is it possible to render it live in Storyboard?

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358

2 Answers2

1

Use like this; Change top , bottom, left, right inset paddings.

@IBDesignable class AttributedLabel: 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

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

    override func intrinsicContentSize() -> CGSize {
        var intrinsicSuperViewContentSize = super.intrinsicContentSize()
        intrinsicSuperViewContentSize.height += topInset + bottomInset
        intrinsicSuperViewContentSize.width += leftInset + rightInset
        return intrinsicSuperViewContentSize
    }
}

Thanks

SwiftDeveloper
  • 7,244
  • 14
  • 56
  • 85
1

Your subclass looks incomplete. As mentioned in the documentation, you should override both of these methods :

public func textRectForBounds(bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect
public func drawTextInRect(rect: CGRect)

Here is an example implementation that should work :

@IBDesignable class AttributedLabel : UILabel
{
    @IBInspectable var padding: CGFloat = 0 {
        didSet {
            self.textInsets = UIEdgeInsets(top: self.padding, left: self.padding, bottom: self.padding, right: self.padding)
        }
    }
    var textInsets = UIEdgeInsetsZero {
        didSet {
            self.invalidateIntrinsicContentSize()
        }
    }

    override func textRectForBounds(bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect
    {
        var insets = self.textInsets
        let insetRect = UIEdgeInsetsInsetRect(bounds, insets)
        let textRect = super.textRectForBounds(insetRect, limitedToNumberOfLines: numberOfLines)
        insets = UIEdgeInsets(top: -insets.top, left: -insets.left, bottom: -insets.bottom, right: -insets.right)
        return UIEdgeInsetsInsetRect(textRect, insets)
    }

    override func drawTextInRect(rect: CGRect) {
        super.drawTextInRect(UIEdgeInsetsInsetRect(rect, self.textInsets))
    }
}

You will not be able to render it live in Interface Builder though.

deadbeef
  • 5,409
  • 2
  • 17
  • 47