3

How to know how much pixels my text is taking in a UILabel ?
I want to insert a small picture in between text.
Can be usefull to adjust my label width.

Peter Hosey
  • 95,783
  • 15
  • 211
  • 370
CiNN
  • 9,752
  • 6
  • 44
  • 57
  • 1
    In measuring text in AppKit, there are no such things as pixels. The string-measurement methods give you their answers in points. One point is 1/72 of an inch. Currently, these numbers are actually pixels because the window's scaling factor is always 1. Someday, this will change: The scaling factor will reflect the resolution of the screen, and string measurements will be in points, as intended. Quartz Debug lets you change the scaling factor; you can use this to make sure you're ready for that day. – Peter Hosey Sep 06 '09 at 05:11
  • but it does give me the distance i need to resize my label and put my imageview just after it ?! – CiNN Sep 06 '09 at 09:05

3 Answers3

14

There are a few methods in NSString added by UIKit that can give you the dimensions of the string if it were to be drawn. The full reference is here. The methods you care about are probably these:

  • sizeWithFont:
  • sizeWithFont:constrainedToSize:
  • sizeWithFont:constrainedToSize:lineBreakMode:
  • sizeWithFont:forWidth:lineBreakMode:
  • sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode:
Kevlar
  • 8,804
  • 9
  • 55
  • 81
2

-[NSString sizeWithFont:] is part of NSString(UIStringDrawing).

2

take a look at this post Pixel Width of the text in a UILabel

Community
  • 1
  • 1