iOS|iOS UILabel设置内边距
有时候我们希望可以设置UILabel的内边距,为了解决这个问题,设计MarginLabel如下,继承自UILabel:
class MarginLabel: UILabel {var contentInset: UIEdgeInsets = .zerooverride func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
var rect: CGRect = super.textRect(forBounds: UIEdgeInsetsInsetRect(bounds, contentInset), limitedToNumberOfLines: numberOfLines)
//根据edgeInsets,修改绘制文字的bounds
rect.origin.x -= contentInset.left;
rect.origin.y -= contentInset.top;
rect.size.width += contentInset.left + contentInset.right;
rect.size.height += contentInset.top + contentInset.bottom;
return rect
}override func drawText(in rect: CGRect) {
super.drawText(in: UIEdgeInsetsInsetRect(rect, contentInset))
}
}
实例化一个MarginLabel:
private lazy var marginLabel: MarginLabel = {
MarginLabel().chain
.text("测试UILabel内边距测试UILabel内边距测试UILabel内边距测试UILabel内边距测试UILabel内边距测试UILabel内边距")
.backgroundColor(UIColor.gray)
.textColor(UIColor.white)
.numberOfLines(0)
.build
}()
不设置内边距的时候:
文章图片
AF6DA567-20B3-47FE-BE0C-406B144BDBD5.png 设置内边距:
marginLabel.contentInset = UIEdgeInsetsMake(10, 10, 10, 10)
【iOS|iOS UILabel设置内边距】效果:
文章图片
CD59CDD8-EA90-4049-9210-B9534A9FDB4C.png
推荐阅读
- 第6.2章(设置属性)
- 2020-04-07vue中Axios的封装和API接口的管理
- iOS中的Block
- 记录iOS生成分享图片的一些问题,根据UIView生成固定尺寸的分享图片
- 2019-08-29|2019-08-29 iOS13适配那点事
- Hacking|Hacking with iOS: SwiftUI Edition - SnowSeeker 项目(一)
- iOS面试题--基础
- 15、IDEA学习系列之其他设置(生成javadoc、缓存和索引的清理等)
- 接口|axios接口报错-参数类型错误解决
- iOS|iOS 笔记之_时间戳 + DES 加密