Pixel Width of Text in UILabel

I need to draw a UILabel. So 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 UILabel is shaded with a line that has the length of the entire label, but the text may be shorter. Is there a way to determine the length of the text in pixels so that the line can be drawn accordingly?

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

Best, Erik

+75
objective-c iphone uilabel
Aug 27 '09 at 12:10
source share
3 answers

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

iOS 7 and above

 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 retrieve font information for your shortcut, as I do above.

Hope this helps :)

+193
Aug 27 '09 at 12:37
source share

The best solution, here in Swift :
Update:
For 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)") 

Old answer:

 yourLabel?.text = "Test label text" // sample label text let labelTextWidth = yourLabel?.intrinsicContentSize().width let labelTextHeight = yourLabel?.intrinsicContentSize().height 
+58
Dec 29 '15 at 6:30
source share

hope this example helps you (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]; 
+1
Nov 10 '14 at
source share



All Articles