2016-08-19 73 views
0

我从storyboard创建了一个标签,现在我试图给该标签填充内容。我创建了一个类并尝试了下面的两种方法,但没有任何工作。请帮忙。UILabel iOS中的填充Swift

override func drawTextInRect(rect: CGRect) { 
     super.drawTextInRect(UIEdgeInsetsInsetRect(rect, UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0))) 

    } 


let padding = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) 


override func 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) 
} 

回答

4

试试这个,我已经使用并从工作这么本身

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

参考:Adding space/padding to a UILabel

+0

我有一个tableViewCell标签,如何申请呢? heeelp。谢谢 。 –

+0

在uitableview的cellForRowat方法中实现相同的单元格标签 –