2017-06-06 132 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。 所以調用線只是顯示單元之前解決此問題。