UILabel中文本的像素宽度 [英] Pixel Width of the text in a UILabel

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

问题描述

我需要绘制一个UILabel。因此,我将UILabel子类化并按如下方式实现:

I need to draw a UILabel striked through. Therefore I subclassed UILabel and implemented it as follows:

@implementation UIStrikedLabel

- (void)drawTextInRect:(CGRect)rect{
    [super drawTextInRect:rect];

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextFillRect(context,CGRectMake(0,rect.size.height/2,rect.size.width,1));
}
@end

UILabel被击穿后会发生什么一条线与整个标签一样长,但文字可以更短。
有没有办法确定文本的长度(以像素为单位),以便可以适当地绘制线条?

What happens is that the the UILabel is striked through with a line being as long as the whole label, but the text can be shorter. Is there a way to determine the length of the text in pixels, such that the line can appropriately be drawn?

我也对任何其他人开放解决方案,如果已知:)

I'm also open to any other solutions, if known :)

最好,
Erik

Best, Erik

推荐答案

NSString有 sizeWithAttributes:可用于此的方法。它返回一个CGSize结构,因此您可以执行与以下内容类似的操作来查找标签内文本的宽度。

NSString has a sizeWithAttributes: method that can be used for this. It returns a CGSize structure, so you could do something similar to the following to find the width of the text inside your label.

CGSize textSize = [[label text] sizeWithAttributes:@{NSFontAttributeName:[label font]}];

CGFloat strikeWidth = textSize.width;



iOS< 7



之前iOS7,您必须使用 sizeWithFont: method。

CGSize textSize = [[label text] sizeWithFont:[label font]];

CGFloat strikeWidth = textSize.width;

UILabel有一个字体属性,可用于动态获取标签的字体详细信息,因为我'我正在做。

UILabel has a font property that you can use to dynamically get the font details for your label as i'm doing above.

希望这会有所帮助:)

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

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