How to determine the length of the text in a UITextfield

本秂侑毒 提交于 2019-12-21 03:36:15

问题


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


回答1:


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



回答2:


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:




回答3:


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



回答4:


In Swift 3.0

let size:CGSize = aTextField.attributedText.size()
let height = size.height
let width = size.width



回答5:


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:




回答6:


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




回答7:


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

[textField.text length]



来源:https://stackoverflow.com/questions/4820355/how-to-determine-the-length-of-the-text-in-a-uitextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!