UILabel 文字边距 [英] UILabel text margin

查看:45
本文介绍了UILabel 文字边距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置 UILabel 的左侧插图/边距,但找不到这样做的方法.标签有一个背景设置,所以仅仅改变它的原点是行不通的.最好在左侧插入 10px 左右的文本.

I'm looking to set the left inset/margin of a UILabel and can't find a method to do so. The label has a background set so just changing its origin won't do the trick. It would be ideal to inset the text by 10px or so on the left hand side.

推荐答案

我通过子类化 UILabel 和覆盖 drawTextInRect: 解决了这个问题:

I solved this by subclassing UILabel and overriding drawTextInRect: like this:

- (void)drawTextInRect:(CGRect)rect {
    UIEdgeInsets insets = {0, 5, 0, 5};
    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}

Swift 3.1:

override func drawText(in rect: CGRect) {
    let insets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 5)
    super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}

Swift 4.2.1:

override func drawText(in rect: CGRect) {
    let insets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
    super.drawText(in: rect.inset(by: insets))
}

正如您可能已经收集到的,这是对 tc. 的回答的改编.它有两个优点:

As you might have gathered, this is an adaptation of tc.'s answer. It has two advantages over that one:

  1. 无需通过发送 sizeToFit 消息来触发它
  2. 它不会单独留下标签框架 - 如果您的标签有背景并且您不希望它缩小,则非常方便

这篇关于UILabel 文字边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆