gpt4 book ai didi

ios - UILabel 边框和填充

转载 作者:搜寻专家 更新时间:2023-10-30 22:21:35 26 4
gpt4 key购买 nike

我想在我的标签内添加填充,以便在标签和边框之间留出空格。我为此创建了一个从 UILabel 扩展的类。

UILabelPadding.swift:

import UIKit

class UILabelPadding: UILabel {

let padding = UIEdgeInsets(top: 30, left: 30, bottom: 30, right: 30)
override func drawText(in rect: CGRect) {
super.drawText(in: UIEdgeInsetsInsetRect(rect, padding))
}

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)
}

override func sizeThatFits(_ size: CGSize) -> CGSize {
let superSizeThatFits = super.sizeThatFits(size)
let width = superSizeThatFits.width + padding.left + padding.right
let heigth = superSizeThatFits.height + padding.top + padding.bottom
return CGSize(width: width, height: heigth)
}


}

我将 myLabel 的类型从 UILabel 更改为 UILabelPadding。在我的 UIViewController 中,我设置了 myLabel 的文本,调用了 sizeToFit(),然后我将边框和背景颜色添加到 myLabel:

   myLabel.text = "label test"
myLabel.sizeToFit()
//background + border
myLabel.layer.borderColor = UIColor(red: 27/255, green: 100/255, blue: 90/255, alpha: 1.0).cgColor
myLabel.layer.backgroundColor = UIColor(red: 27/255, green: 100/255, blue: 90/255, alpha: 1.0).cgColor
myLabel.layer.cornerRadius = 9
myLabel.layer.masksToBounds = true
myLabel.layer.borderWidth = 1

添加了边框和背景色,但填充不起作用。当我调试时,永远不会调用 sizeThatFits()。

有什么帮助吗?

最佳答案

我解决了这个问题!

对于那些面临同样问题的人:

1- 创建一个继承自 UILabel 的类:

UILabelPadding.swift:

class UILabelPadding: UILabel {

let padding = UIEdgeInsets(top: 2, left: 8, bottom: 2, right: 8)
override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: padding))
}

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)
}



}

2- 将标签类型设置为 UILabelPadding 并确保该类型也在 Storyboard中设置。

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

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