UILabel文本边距 [英] UILabel text margin

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

问题描述

我想要设置UILabel的左插入/边距,并且找不到一个方法。标签有一个背景设置,所以只是改变它的原点不会做的伎俩。

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中等效:

equivalent in Swift:

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

已收集,这是 tc。的回答的改编。它有两个优点:

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


  1. 没有必要通过发送 sizeToFit

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

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