Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pixel Width of the text in a 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 

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 :)

Best, Erik

like image 594
Erik Avatar asked Aug 27 '09 12:08

Erik


People also ask

How do I get the width of a text in Swift?

Swift-5. Use intrinsicContentSize to find the text height and width.

How is font width calculated?

A font is often measured in pt (points). Points dictate the height of the lettering. There are approximately 72 (72.272) points in one inch or 2.54 cm. For example, the font size 72 would be about one inch tall, and 36 would be about a half of an inch.


1 Answers

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.

iOS 7 and higher

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

iOS <7

Prior to iOS7, you had to use the sizeWithFont: method.

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

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

Hope this helps :)

like image 157
Harry Avatar answered Sep 22 '22 10:09

Harry