我正在尝试在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吗?
答案 0 :(得分:9)
请如下更新您的代码
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))
}
}
答案 1 :(得分:6)
Imho,您还必须更新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
}
}
答案 2 :(得分:0)
使用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
答案 3 :(得分:0)
对于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))
}
答案 4 :(得分:0)
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))
}}