Truncating text to fit fixed size tableviews.

View based tableviews may contain many subviews. For example, a twitter tableview needs to include outlets for an icon image, date, user name, real name, retweeting, favouriting, replying, following and the text of the tweet. In my twitter implementation I had trouble implementing the resizing of the tableview row to show tweets that extended over more than 2 lines. Instead of resizing the view I decided to truncate tweets that were more than 2 lines long and only show first 2 lines of the tweet. Apple in fact provides the necessary code to count the number of lines needed to display an attributed string in a view. This code was easy to adapt to my purpose. The work is done in the tableview delegate method tableView:viewForTableColumn:row. I created a ‘Tweet’ object to hold the relevant information about each tweet (user details, date, text etc). The ‘Tweets’ array holds the downloaded tweets. RBTwitterCellView is the top view in the tableview. It contains all the subviews mentioned above. The relevant parts of tableView:viewForTableColumn:row are given below.


- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
RBTwitterCellView *result = [tableView makeViewWithIdentifier:tableColumn.identifier owner:self];
Tweet *tempTweet = [tweets objectAtIndex:row];
.
(allocate values to the various subviews of 'result' and created the attributed tweet text string)
.
[[[result tweetTextView] textStorage] setAttributedString:attributedTextString];

// The following code calculates the number of lines required to display the tweet in the given view within the tableview.
// If the number of lines required is more than 2 I truncate the tweet after the second line (line2index points to the end
// of the second line).
NSLayoutManager *layoutManager = [[result tweetTextView] layoutManager];
NSUInteger numberOfLines, index, line2index, numberOfGlyphs = [layoutManager numberOfGlyphs];
NSRange lineRange;
for (numberOfLines = 0, index = 0; index 2){
[[result tweetField] setString:[[attributedStatusString string]substringToIndex:line2index]];
}

return result;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: