I want to display a single-line text field using UITextField and I need to know before displaying it, the proper size for its containing UICollectionViewCell. The text can be one of multiple font sizes and I need to get the right height for displaying it comfortably.
Since the text is not known in advance (it can be edited by the user), I can't use NSAttributedString
's -size
and -boundingRectWithSize:options:context:
with anything but dummy text, in which case I can't really trust the resulting size to hold any piece of text, right?
I guess my question is: Is there a rule of thumb about typography in general, or some useful API I'm not aware of, that would allow me to determine that for displaying text at X
pt, I need a text field with a height of Y
px.
UITextField
implements the sizeThatFits:
method. So the most reliable way to get the size of your text field is to actually create one, set it up like you would set up your real text fields, and ask it for a suitable size. You don't even have to give it placeholder text, because UITextField
will choose the size based on its font, not on its text.
UITextField *dummy = [[UITextField alloc] init];
dummy.font = [UIFont systemFontOfSize:20];
dummy.borderStyle = UITextBorderStyleRoundedRect;
CGFloat requiredHeight = [dummy sizeThatFits:CGSizeMake(HUGE_VALF, HUGE_VALF)].height;
// requiredHeight == 30 in my test
If your deployment target is iOS 6.0 or later, you can instead use the intrinsicContentSize
property, like this:
CGFloat requiredHeight = dummy.intrinsicContentSize.height;
// requiredHeight == 30 in my test
Note that sizeThatFits:
still works in iOS 6, but intrinsicContentSize
is a little easier to understand.
iOS always returns a height of 30 units when the borderStyle is RoundedRect. If you want to compute the height required by a custom font, you have to change the borderStyle to any other value, compute the height, and change the borderStyle back.
textField.borderStyle = UITextBorderStyle.None;
let sizeThatFits = textField.sizeThatFits(CGSize(width:textField.bounds.width, height: CGFloat.max));
textField.bounds.height = sizeThatFits.height;
textField.borderStyle = UITextBorderStyle.RoundedRect;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.