问题
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