14

I have a UITextField from which I'd like to determine the width of the entered text.

The bounds property has just the size of the Textfield but not of the text

gabac
  • 2,012
  • 6
  • 21
  • 30

7 Answers7

14
CGFloat width =  [aTextField.text sizeWithFont:aTextField.font].width;
Martin Babacaev
  • 6,110
  • 2
  • 18
  • 33
8

Now that sizeWithFont: is deprecated in iOS 7.0 use

CGFloat width =  [tf.text sizeWithAttributes: @{NSFontAttributeName:tf.font}].width;

https://developer.apple.com/library/ios/documentation/UIKit/Reference/NSString_UIKit_Additions/#//apple_ref/occ/instm/NSString/sizeWithAttributes:

gwest7
  • 1,346
  • 17
  • 25
6

If you are looking for character count it is this

int textLength = [someTextField.text length]

If you are looking for pixel width try this

CGSize size = [someTextField.text sizeWithFont:someTextField.font];
//size.width contains the width
Joe
  • 56,349
  • 8
  • 124
  • 132
3

In Swift 3.0:

let size = aTextField.attributedText?.size()
let height = size.height
let width = size.width
aheze
  • 16,189
  • 4
  • 33
  • 81
miletliyusuf
  • 544
  • 5
  • 9
0
CGSize size = [myTextField.text sizeWithFont:myTextField.font];

Documentation here: http://developer.apple.com/library/ios/documentation/UIKit/Reference/NSString_UIKit_Additions/Reference/Reference.html#//apple_ref/occ/instm/NSString/sizeWithFont:

theChrisKent
  • 14,981
  • 3
  • 59
  • 61
0

Does this Pixel Width of the text in a UILabel help ?

Community
  • 1
  • 1
HeikoG
  • 1,803
  • 1
  • 20
  • 29
-1

textField is delegate which is attac in interface builder than......

[textField.text length]

The deals dealer
  • 1,006
  • 2
  • 8
  • 16