在這裏,我試圖在文本週圍添加一些填充(左,右,上和下)的標籤。 這一問題已經在SOF和閱讀他們幾個後相關的帖子,我試圖用一個解決方案提出here:UILabel上的文本填充
這是我的子類的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
,這是結果:
如果我此行添加到以上兩個:
label.lineBreakMode = .byWordWrapping
結果是:
我還設置了一些限制。所有這些工作都有95%的時間。任何人都可以看到有什麼問題?
你有沒有設置'numberOfLines = 0'和'lineBreakMode = .byWordWrapping '? – Priya
我已經設置numberOfLines = 0,但不lineBreakMode = .byWordWrapping。 我實際上有多個案例,多條線完美的工作。 它並沒有解決問題,如果我設置lineBreakMode = .byWordWrapping,我編輯我的帖子添加細節,請看看。 – Michel
您是否爲標籤設置了靜態高度約束? – Priya