swift-UILabel

添加内间距

import UIKit

class ViewController: UIViewController {

    let customLabel = WarningLabel()
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        customLabel.text = "asadlfjsaldjfdsfasadlfjsaldjfdsfasadlfjsaldjfdsfasadlfjsaldjfdsfasadlfjsaldjfdsfasadlfjsaldjfdsfasadlfjsaldjfdsfasadlfjsaldjfdsfasadlfjsaldjfdsfasadlfjsaldjfdsfasadlfjsaldjfdsfasadlfjsaldjfdsfasadlfjsaldjfdsfasadlfjsaldjfdsfasadlfjsaldjfdsfasadlfjsaldjfdsfasadlfjsaldjfdsfasadlfjsaldjfdsfasadlfjsaldjfdsfasadlfjsaldjfdsfasadlfjsaldjfdsfasadlfjsaldjfdsfasadlfjsaldjfdsfasadlfjsaldjfdsfasadlfjsaldjfdsf"
        customLabel.textColor = UIColor.black
        customLabel.font = UIFont.systemFont(ofSize: 15)
        
        customLabel.backgroundColor = UIColor.red
        customLabel.layer.borderWidth = 2
        customLabel.layer.borderColor = UIColor.blue.cgColor
        customLabel.textAlignment = .left
        customLabel.translatesAutoresizingMaskIntoConstraints = false
        customLabel.contentInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)//关键点,需要添加这个属性
        customLabel.layer.cornerRadius = 10.0
        customLabel.sizeToFit()
        
        view.addSubview(customLabel)
        customLabel.translatesAutoresizingMaskIntoConstraints = false
        customLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 50).isActive = true
        customLabel.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 50).isActive = true
        customLabel.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -50).isActive = true
        customLabel.numberOfLines = 0
        
    }
}
class WarningLabel: UILabel {
    var contentInsets: UIEdgeInsets = UIEdgeInsets.zero
    
    //将label显示文本的区域缩小
    //结果是文本将不会被绘制在 contentInsets 定义的内边距区域中,而是在缩小后的 rect 内绘制。
    override func drawText(in rect: CGRect) {
        let insets = contentInsets
        super.drawText(in: rect.inset(by: insets))
    }
    
    //调整标签的固有内容尺寸
    //默认情况下,UILabel 的固有内容尺寸只考虑文本内容的大小。
    //通过重写 intrinsicContentSize 属性,我们可以告诉布局系统,标签需要比默认的尺寸更大,以包含内边距。
    override var intrinsicContentSize: CGSize {
        let size = super.intrinsicContentSize
        let width = size.width + contentInsets.left + contentInsets.right
        let height = size.height + contentInsets.top + contentInsets.bottom
        return CGSize(width: width, height: height)
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值