2016-08-22 19 views
0

は、これは私のサブクラスはUILabelのためにどのように見えるかです:@IBDesignableプロパティを使用してUILabelのパディングを設定する方法は?

@IBDesignable class AttributedLabel: UILabel { 

    @IBInspectable var padding: CGFloat = 0 

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

私は正しくストーリーボードにpaddingを設定するが、パディングがまだ0あるので、それは仕事をdoesntの。

これを機能させるにはどうすればよいですか?それをストーリーボードにライブレンダリングすることは可能ですか?

答えて

0

このように使用します。上、下、左、右の埋め込みパディングを変更します。

@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 
    } 
} 

おかげ

1

あなたのサブクラスが不完全になります。文書で述べたように、あなたはこれらのメソッドの両方をオーバーライドする必要があります:あなたはしかしInterface Builderでのライブ、それをレンダリングすることはできません

@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)) 
    } 
} 

:ここ

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

は動作するはずの実装例であります。

関連する問題