UILabel中文本的像素宽度

我需要画一个UILabel通过。 因此,我分类UILabel和实施它如下:

@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是通过与整个标签一样长的一条线穿过,但文本可以更短。 有没有一种方法来确定像素的文本的长度,这样的行可以适当地绘制?

我也打开任何其他解决scheme,如果知道:)

最好的,Erik

NSString有一个可用于此的sizeWithAttributes:方法。 它返回一个CGSize结构,所以你可以做类似于下面的事情来find你的标签内的文本的宽度。

iOS 7及更高版本

 CGSize textSize = [[label text] sizeWithAttributes:@{NSFontAttributeName:[label font]}]; CGFloat strikeWidth = textSize.width; 

iOS <7

在iOS7之前,你必须使用sizeWithFont:方法。

 CGSize textSize = [[label text] sizeWithFont:[label font]]; CGFloat strikeWidth = textSize.width; 

UILabel有一个字体属性,您可以使用它来dynamic获取您的标签的字体细节,因为我在上面做的。

希望这可以帮助 :)

更好的解决scheme,在Swift中
更新:
对于Swift 3/4

 @IBOutlet weak var testLabel: UILabel! // in any function testLabel.text = "New Label Text" let width = testLabel.intrinsicContentSize.width let height = testLabel.intrinsicContentSize.height print("width:\(width), height: \(height)") 

老答案:

 yourLabel?.text = "Test label text" // sample label text let labelTextWidth = yourLabel?.intrinsicContentSize().width let labelTextHeight = yourLabel?.intrinsicContentSize().height 

希望这个示例可以帮助你(iOS> 7)

 NSString *text = @" // Do any additional setup after loading the view, typically from a nib."; CGRect rect = CGRectZero; NSDictionary *attrDict = @{NSFontAttributeName : [UIFont systemFontOfSize:17]}; rect = [text boundingRectWithSize:CGSizeMake(100,9999) options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:attrDict context:Nil]; UILabel *lbl = [[UILabel alloc] init]; lbl.text = text; rect.origin = CGPointMake(50, 200); lbl.frame = rect; lbl.lineBreakMode = NSLineBreakByWordWrapping; lbl.numberOfLines = 0; [self.view addSubview:lbl];