views:

45

answers:

3

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 alloc] 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.

A: 

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;

davydotcom
Right, but if I set it to 2, then I will lose text if it's longer than 2 lines. I'm trying to figure out what to set `numberOfLines` to.
Moshe
A: 

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.

Eiko
The problem is that I don't know how long my headlines will be and I don't know how many lines to use. I need to calculate this on the fly for each headline.
Moshe
+1  A: 

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.)

Yuji
I'm not actually implementing the line breaks, I am just setting the `textLabel` s "lines" property.
Moshe
Ah, then that makes sense :) Then you should say that in your question... :p
Yuji
@Yuji - ok, I added it.
Moshe