String length with given font to fit UITextView

后端 未结 4 754
遇见更好的自我
遇见更好的自我 2021-01-01 00:17

I need to move text that the user has entered into a large multi-line UITextView into a smaller (but still multi-line) UITextView*. If the user has

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-01 00:54

    This isn't actually a fix but it does provide a good starting poing for the calculation.

    If you use NSString's sizeWithFont: constrainedToSize: lineBreakMode: you get a vertical height for your text. If you divide that by your font's leading height, you get the number of lines in the whole string. Dividing [NSString count] by that number gives you an approximation to number of characters per line. This assumes the string is homogeneuous and will be inaccurate if someone types (e.g.) 'iiiiiiiiiii..." as oposed to "MMMMMMMMM...".

    You can also divide you bounding box by the relevent font's leading height to get the number of lines that fit within your bounding box.

    Multiplying characters per line by number of lines gives you a starting point for finding text that fits.

    You could calculate the margin for error in this figure by doing the same calculation for those 'iiiiii...' and "MMMMMM...'" strings.

提交回复
热议问题