2017-11-11 199 views
1

在這裏,我試圖在文本週圍添加一些填充(左,右,上和下)的標籤。 這一問題已經在SOF和閱讀他們幾個後相關的帖子,我試圖用一個解決方案提出hereUILabel上的文本填充

這是我的子類的UILabel代碼:

import UIKit 

class LuxLabel: UILabel { 
    //let padding: UIEdgeInsets 
    var padding: UIEdgeInsets = UIEdgeInsets.zero { 
     didSet { 
      self.invalidateIntrinsicContentSize() 
     } 
    }  

    // Create a new PaddingLabel instance programamtically with the desired insets 
    required init(padding: UIEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)) { 
     self.padding = padding 
     super.init(frame: CGRect.zero) 
    } 

    // Create a new PaddingLabel instance programamtically with default insets 
    override init(frame: CGRect) { 
     padding = UIEdgeInsets.zero // set desired insets value according to your needs 
     super.init(frame: frame) 
    } 

    // Create a new PaddingLabel instance from Storyboard with default insets 
    required init?(coder aDecoder: NSCoder) { 
     padding = UIEdgeInsets.zero // set desired insets value according to your needs 
     super.init(coder: aDecoder) 
    } 

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

    // Override `intrinsicContentSize` property for Auto layout code 
    override var 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) 
    } 
} 

它是基於PaddingLabel(參考上面的鏈接)。

它主要運行良好,但由於某些原因,我不明白,有些情況下出現問題並且顯示被截斷。

這是一個例子:

的字符串把標籤是:「它有一個方形和藍色」

創建標籤的代碼是:

let label = LuxLabel(padding: UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)) 
label.numberOfLines = 0 

,這是結果:

enter image description here

如果我此行添加到以上兩個:

label.lineBreakMode = .byWordWrapping

結果是:

enter image description here

我還設置了一些限制。所有這些工作都有95%的時間。任何人都可以看到有什麼問題?

+0

你有沒有設置'numberOfLines = 0'和'lineBreakMode = .byWordWrapping '? – Priya

+0

我已經設置numberOfLines = 0,但不lineBreakMode = .byWordWrapping。 我實際上有多個案例,多條線完美的工作。 它並沒有解決問題,如果我設置lineBreakMode = .byWordWrapping,我編輯我的帖子添加細節,請看看。 – Michel

+0

您是否爲標籤設置了靜態高度約束? – Priya

回答

1

嘗試調用invalidateIntrinsicContentSize:

var padding: UIEdgeInsets = UIEdgeInsets.zero { 
    didSet { 
     self.invalidateIntrinsicContentSize() 
    } 
} 

編輯:

我嘗試了多種不同的選擇。如果更新frame sizelayoutSubviews使絕招intrinsicContentSize,但我不知道是否有更好的方式來做到這一點:

override func layoutSubviews() { 
    super.layoutSubviews() 
    self.frame.size = self.intrinsicContentSize 
} 
+0

我試過了,按照你的建議,用「var padding」代替「let padding」,但不幸的是它沒有任何區別。 – Michel

+0

@Michel明天我會試着重現它,如果我找到一些我會讓你知道的。 –

+0

我在GitHub(https://github.com/zaxonus/TextPad)上發佈了一個項目來展示這個問題。 – Michel