[英]Set insets on UILabel
我正在尝试在 UILabel 中设置一些插图。 它工作得很好,但现在UIEdgeInsetsInsetRect
已被CGRect.inset(by:)
取代,我不知道如何解决这个问题。
当我尝试将CGRect.inset(by:)
与我的插图一起使用时,我收到了UIEdgeInsets
不可转换为CGRect
的消息。
class TagLabel: UILabel {
override func draw(_ rect: CGRect) {
let inset = UIEdgeInsets(top: -2, left: 2, bottom: -2, right: 2)
super.drawText(in: CGRect.insetBy(inset))
// super.drawText(in: UIEdgeInsetsInsetRect(rect, inset)) // Old code
}
}
任何人都知道如何将插图设置为 UILabel?
恕我直言,您还必须更新intrinsicContentSize
:
class InsetLabel: UILabel {
let inset = UIEdgeInsets(top: -2, left: 2, bottom: -2, right: 2)
override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: inset))
}
override var intrinsicContentSize: CGSize {
var intrinsicContentSize = super.intrinsicContentSize
intrinsicContentSize.width += inset.left + inset.right
intrinsicContentSize.height += inset.top + inset.bottom
return intrinsicContentSize
}
}
请更新您的代码如下
class TagLabel: UILabel {
override func draw(_ rect: CGRect) {
let inset = UIEdgeInsets(top: -2, left: 2, bottom: -2, right: 2)
super.drawText(in: rect.insetBy(inset))
}
}
此代码与接受的答案不同,因为接受的答案使用 insetBy(inset) 而此答案使用 inset(by: inset)。 当我在 iOS 10.1 和 Swift 4.2.1 自动完成中添加这个答案时,没有给你 rect.inset(by:),我不得不手动输入它。也许它在 Swift 5 中可以,我不确定
对于 iOS 10.1
和Swift 4.2.1
使用rect.inset(by:
这个:
override func draw(_ rect: CGRect) {
let inset = UIEdgeInsets(top: -2, left: 2, bottom: -2, right: 2)
super.drawText(in: rect.inset(by: inset))
}
使用UIEdgeInsetsInsetRect的“旧代码”应该可以正常工作。
https://developer.apple.com/documentation/coregraphics/cgrect/1454218-insetby
编辑#1:
iOS 12 API更改:
https://developer.apple.com/documentation/coregraphics/cgrect/1624499-inset?changes=latest_minor
Swift 5用 draw(...) 替换方法 drawText(...)
extension UILabel {
open override func draw(_ rect: CGRect) {
let inset = UIEdgeInsets(top: -2, left: 2, bottom: -2, right: 2)
super.draw(rect.inset(by: inset))
}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.