I'm making an RSS parser for iPhone and iPod Touch and I need to be able to set the number of lines shown in each cell for each article. I'd like to break every 39 characters, which is the most that fits on a line at the font size that I'm using.
I'd like to take the number of characters in a string and divide it by the number of characters per line. I'd like to have an integer as an answer, rounded up where necessary.
This is what I have so far. What is wrong?
NSNumber *lines = [[NSNumber alloc] initWithInteger:[cell.textLabel.text length]/kLineLength];
NSNumberFormatter *formatter = [[NSNumberFormatter allo开发者_开发问答c] init];
[formatter setRoundingMode:NSNumberFormatterRoundUp];
[formatter setRoundingIncrement:[[[NSNumber alloc]initWithInteger:1]autorelease]];
NSNumber *roundedLines = [[NSNumber alloc]initWithInteger: [[formatter numberFromString:[lines stringValue]]integerValue]];
[cell.textLabel setNumberOfLines:[roundedLines integerValue]];
[roundedLines release];
[formatter release];
[lines release];
EDIT
I'm not after line breaks so much as knowing how many lines to give the label. So, while I'm effectively setting line-breaks, I'm not really doing that. I let the iOS figure out where to break, I just tell it how many lines to use.
Don't do that yourself. Let the UILabel
or UITextView
or UIWebView
do that for you. Each letters have different width. It doesn't make any sense to insert line breaks for every N
characters.
I mean, typesetting is a sophisticated art, cultivated since the days of Gutenberg for hundreds of years. I don't dare to do that myself. Leave that to the experts (i.e. API implementers.)
Not sure if this complicated solution you gave was a joke :-)
int numberOfCharacters = ....;
int kLineLength = 39;
int lines = (numberOfCharacters + kLineLength - 1) / kLineLength;
No need for any formatters etc.
Edit: You will probably disappointed with fixed line widths anyway, as word wrapping will (should!) make your lines shorter anyway.
Im not sure what you are exactly trying to accomplish here but you may not be able to use cell.textLabel and have to use a custom UITableViewCell..
Also the UILabel object automatically produces the line breaks where necessary if you set the cell.textLabel.numberOfLines = 2;
精彩评论