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,062
  • 6
  • 21
  • 30

7 Answers7

14
CGFloat width =  [aTextField.text sizeWithFont:aTextField.font].width;
Martin Babacaev
  • 6,240
  • 2
  • 19
  • 34
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,556
  • 19
  • 26
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,979
  • 9
  • 128
  • 135
3

In Swift 3.0:

let size = aTextField.attributedText?.size()
let height = size.height
let width = size.width
aheze
  • 24,434
  • 8
  • 68
  • 125
miletliyusuf
  • 982
  • 1
  • 10
  • 12
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
  • 15,029
  • 3
  • 61
  • 62
0

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

Community
  • 1
  • 1
HeikoG
  • 1,793
  • 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