Reputation: 4994
I have to limit the amount of characters or length of UITableView's cell texts . Because each cell displays a very long long long text and I have to limit these text into for example 140 characters . because it causes slow scrolling and memory issues and etc ...
I am loading cell texts from an SQL DB :
appClass = (AppDelegate *)[[UIApplication sharedApplication] delegate];
readerClass = (Reader *)[appClass.wordList objectAtIndex:indexPath.row];
cell.textLabel.text=readerClass.Name;
Thanks.
Upvotes: 1
Views: 1140
Reputation: 4018
Use:
cell.textLabel.text = (readerClass.Name.length > 140 ? [readerClass.Name substringToIndex:140] : readerClass.Name);
This sets the full readerClass.Name
when it has fewer than 140 characters and sets the first 140 characters if it is longer.
Also, I'm assuming you have a UILabel in the UITableViewCell, which automatically appends ...
(ellipsis) when text is truncated. If not, you can add ellipsis yourself:
cell.textLabel.text = (readerClass.Name.length > 140 ? [[readerClass.Name substringToIndex:137] stringByAppendingString:@"..."] : readerClass.Name);
Just at add on to this question, since you asked about getting the first line only:
// get first line break range
NSRange rangeOfFirstLineBreak = [cell.textLabel.text rangeOfCharacterFromSet:[NSCharacterSet newlineCharacterSet]];
// check if first line break range was found
if (rangeOfFirstLineBreak.location == NSNotFound) {
// if it was, extract the first line only and update the cell text
cell.textLabel.text = [cell.textLabel.text substringToIndex:rangeOfFirstLineBreak.location];
}
Upvotes: 4
Reputation: 8298
This should work. It also adds '...'
NSString *name = readerClass.Name;
if( name.length > 140 ){
name = [place substringToIndex:140];
name = [NSString stringWithFormat:@"%@...", name];
}
cell.textLabel.text= name;
Upvotes: 0
Reputation: 12566
Something like this:
NSRange stringRange = {0, MIN([readerClass.Name length], 140)};
cell.textLabel.text = [readerClass.Name substringWithRange:stringRange];
Upvotes: 0