How can I make a UITextView
change its font size so that all of the text fits within a maximum of two lines? If the text fits one or two lines perfectly then I don't want the font size to change. But if the text is any longer, I need it to get smaller. Thanks.
I believe you have a great reason to use UITextView
, and thus I think this can be little tricky and needs a lot of testing to see it actually works just as you expected.
What I would suggest is to calculate number of rows by:
let font = yourFont
let size = yourTextView.contentSize
let inset = yourTextView.textContainerInset
let rows = (size.height - inset.top - inset.bottom) / font.lineHeight
Get rows inside textView
's delegate method, something like textView:shouldChangeTextIn:...
for instance, and change font size according to this information.
Another suggestion is to make invisible UILabel
with properties set like below:
label.font = yourFont
label.frame = CGRect(x: 0, y: 0, width: yourTextView.contentSize.width, height: yourTextView.contentSize.height)
label.numberOfLines = 2
label.adjustFontSizeToFitWidth = true
Then inside textView
's delegate method, update label
's text and
textView.font = label.font
I'm not sure either of these will actually work since I haven't tested them for myself, but I hope this may help you to set a start point for this problem.
Unless you have a specific need to be using a UITextView
, I recommend using a UILabel
. This code limits a UILabel
to two lines and makes its text auto-shrink:
label.numberOfLines = 2
label.adjustsFontSizeToFitWidth = true
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.