gpt4 book ai didi

ios - UILabel 上的文本填充

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:30:57 25 4
gpt4 key购买 nike

在这里,我试图在文本周围添加一些填充(左、右、上和下)的标签。这个问题在 SOF 上有相关的帖子,在阅读了其中的一些之后,我尝试使用建议的解决方案 here :

这是我的子类化 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(参见上面的链接)。

大部分情况下它运行良好,但由于某些我不明白的原因,有时会出现问题并且显示被截断。

这是一个例子:

要放在标签上的字符串是:

"It has a square shape and a blue color."

创建标签的代码是:

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% 的时间都有效。谁能看出问题出在哪里?

最佳答案

尝试调用 invalidateIntrinsicContentSize:

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

编辑:

我尝试过不同的选择。如果您在 layoutSubviews 中使用 intrinsicContentSize 更新 frame size 就可以解决问题,但我不知道是否有更好的方法它:

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

关于ios - UILabel 上的文本填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47234008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com