开发者

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


CGFloat width =  [aTextField.text sizeWithFont:aTextField.font].width;


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:


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


In Swift 3.0:

let size = aTextField.attributedText?.size()
let height = size.height
let width = size.width


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:


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


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

[textField.text length]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜