[英]iOS - UILabel insets to zero is not worling
我正在关注教程https://spin.atomicobject.com/2017/08/04/swift-extending-uilabel/因为我想删除 label 里面的填充。
该代码似乎非常有用,但我不让它工作:
import UIKit
@IBDesignable
class EdgeInsetLabel: UILabel {
var textInsets = UIEdgeInsets.zero {
didSet { invalidateIntrinsicContentSize() }
}
override func textRect(forBounds bounds: CGRect,
limitedToNumberOfLines numberOfLines: Int) -> CGRect {
let insetRect = bounds.inset(by: textInsets)
let textRect = super.textRect(forBounds: insetRect, limitedToNumberOfLines: numberOfLines)
let invertedInsets = UIEdgeInsets(top: -textInsets.top,
left: -textInsets.left,
bottom: -textInsets.bottom,
right: -textInsets.right)
return textRect.inset(by: invertedInsets)
}
override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: textInsets))
}
}
extension EdgeInsetLabel {
@IBInspectable
var leftTextInset: CGFloat {
set { textInsets.left = newValue }
get { return textInsets.left }
}
@IBInspectable
var rightTextInset: CGFloat {
set { textInsets.right = newValue }
get { return textInsets.right }
}
@IBInspectable
var topTextInset: CGFloat {
set { textInsets.top = newValue }
get { return textInsets.top }
}
@IBInspectable
var bottomTextInset: CGFloat {
set { textInsets.bottom = newValue }
get { return textInsets.bottom }
}
}
插图基于字体——而不是单个字符:
因此,使用UILabel
中的默认系统字体,添加一些其他字符:
如果要将背景剪辑到单个字符的边界框,则需要使用Text Kit
功能。 这是一个很好的起点: 使用 Text Kit 绘制和管理文本
使用myLabel.sizeToFit()
删除 label 周围的任何可移动空间。
您缺少EdgeLabel
子类中覆盖的textRect(forBounds:)
部分:
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
let insetRect = UIEdgeInsetsInsetRect(bounds, textInsets)
let textRect = super.textRect(forBounds: insetRect, limitedToNumberOfLines: numberOfLines)
let invertedInsets = UIEdgeInsets(top: -textInsets.top,
left: -textInsets.left,
bottom: -textInsets.bottom,
right: -textInsets.right)
return UIEdgeInsetsInsetRect(textRect, invertedInsets)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.