Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine the length of the text in a UITextfield

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

like image 926
gabac Avatar asked Jan 27 '11 18:01

gabac


People also ask

How do I limit characters in UITextField Swift?

If you have a UITextField or UITextView and want to stop users typing in more than a certain number of letters, you need to set yourself as the delegate for the control then implement either shouldChangeCharactersIn (for text fields) or shouldChangeTextIn (for text views).

What is UITextField in swift?

An object that displays an editable text area in your interface.


2 Answers

CGFloat width =  [aTextField.text sizeWithFont:aTextField.font].width;
like image 83
Martin Babacaev Avatar answered Oct 11 '22 17:10

Martin Babacaev


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:

like image 44
gwest7 Avatar answered Oct 11 '22 18:10

gwest7