Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

iphone - Can't get UITextField to autoshrink text

I have a UITextField on a table view cell, and when it's text becomes too long I would like the font size to decrease. I want to make it very clear that I am talking about a UITextField, not a UILabel or a UITextView. The reason I say this is because I have seen this question pop up several times and the answers were all based on UILabel instead of UITextField. For example, someone asked "I can't get my UITextField to autoshrink" and the answer was "make sure it's numberOfLines is set to 1". To the best of my knowledge, a UITextField does not even have that property and is a single line control.

I have tried:

  • in IB setting the font to system 14.0, minFontSize to 7 and checking the "adjust to fit" box
  • in code in tableView:cellForRowAtIndexPath:
ptCell.name.font = [UIFont systemFontOfSize: 14.0];
ptCell.name.adjustsFontSizeToFitWidth = YES;
ptCell.name.minimumFontSize = 7.0;

but neither of these have worked. By that I mean that instead of the text shrinking it truncates the tail.

Does anyone know what I am missing? Presumably this should work because I have seen other questions complaining that it is doing that when the user does not want it to.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I had the same problem. The UITextField stoped shrinking the text when it was too long, but instead it resized itself and grew outside its 'bounds'.

The solution that helped me was to set width constraint on given UITextField. After that it did not grew anymore, instead the text inside got smaller as intended. (Of course you have to set minFontSize and check the "adjust to fit" box in storyboard.)

I know it's kind of a late, but if anyone else will find this question via google as I did...it might just help.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...