I have 4 lines UILabel with exact frame and font.
I need to know if this string fits the label and what is the index of the last character which fits.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The kernel of the answer is in Cupcake’s referenced posting. Anyway, you can use
sizeWithFont:constrainedToSize:lineBreakMode:to figure out what the size of a frame would be with a particular font in a label of a given width given a specific word wrapping, e.g.Set
sizeConstraintto be the same width of your label, but set the height to be larger. If the resultingsize.heightis larger than your UILabel, then your string is too long. Theoretically, you could remove the last character/word and try again and repeat until it fits.If you think the strings might be very long, you might want to go the other way, start with a short portion of the string and keep adding characters until it’s too large, and then you know the last character.
Either way, this iterative calculation of the size can be pretty cpu intensive operation, so be careful.
Update:
Here is an algorithm that returns the length of
NSStringthat can fit into theUILabelin question using the default font (but ignoring minimum font size):You could probably make this more efficient if you, for example, checked if word break mode, jumping to the next word separator and then calling
sizeWithFont, but for smallUILabels this might be sufficient. If you wanted to leverage word-wrap logic to minimize the number of times you callsizeWithFont, you might have something like:Perhaps the character set used here isn’t quite right (should you include hyphens, for example), but it’s probably pretty close and far more efficient than doing character by character, if you don’t need to do that.