2017-06-06 127 views
1

我一直在使用的StackOverflow的popular thread解决自动布局问题设置我的UILabel填充。 这个线程基本上是一个UILabel扩展。答案不能设置的UILabel填充在tableViewcell

部分是:

class NRLabel : UILabel { 

    var textInsets = UIEdgeInsets.zero { 
     didSet { invalidateIntrinsicContentSize() } 
    } 

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

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

一切工作正常,填充已添加,但我需要重新加载tableViewcell看到效果。

我已重写我的customCell的viewWillLayoutSubviews()函数像这样填充

self.chatLabel.textInsets = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10) 

,效果是这样的。

enter image description here

你看,第一个标签得到它的重装电池后填充。

PLS建议如何使用,使这个问题解决了上面提到的扩展来实现的UILabel填充。

+0

目前尚不清楚你想要的目的。你是什么想要一个带填充的UILabel?任何理由不把标签作为UIView的子视图,只使用自动布局和约束? – DonMag

+0

@elk_cloner你可以在你的单元格中使用cell.dequeue吗? –

+0

我已经使用了自定义单元格。我想与填充 –

回答

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 var intrinsicContentSize : CGSize { 
      var intrinsicSuperViewContentSize = super.intrinsicContentSize 
      intrinsicSuperViewContentSize.height += topInset + bottomInset 
      intrinsicSuperViewContentSize.width += leftInset + rightInset 
      return intrinsicSuperViewContentSize 
     } 
0

使用您NRLabel类,这个工作正常,我。该theLabel在故事板TableViewCell原型添加,设置为允许自动调整大小的行限制。

class PaddedLabelCell : UITableViewCell { 

    @IBOutlet weak var theLabel: NRLabel! 

    override func awakeFromNib() { 
     super.awakeFromNib() 
     self.setupLabel() 
    } 

    func setupLabel() -> Void { 
     theLabel.layer.cornerRadius = 8.0 
     theLabel.layer.masksToBounds = true 
     theLabel.textInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) 
     // any other setup stuff can go here.... 
    } 

} 
0

NRLabel中没有任何内容告诉它在textInsets属性更改时重绘。你需要做这样的事情:

var textInsets = UIEdgeInsets.zero { 
    didSet { 
     invalidateIntrinsicContentSize() 
     setNeedsDisplay() 
    } 
} 

所以当textInsets属性更改现在NRLabel将与新的文本插图重新绘制。

-1

一些长期劳累小时后我才发现这是我从来没有尝试过的解决方案,我不知道为什么。 :(

的cellForRowAtIndexPath我只是写这在customCell的文件就行了。

返回小区之前就叫这条线。

cell.chatLabel.textInsets = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10) 

背后的原因可能是,小区绘制所有的功能,但它并没有得到太多刷新它的UI。 所以调用线只是显示单元之前解决此问题。