user1163876
user1163876

Reputation: 25

UITextView, Line Numbers Not Aligned

I have a UITextView which I am using to display text. Along the side I have a UITableView that I am using to display the line Numbers. The problem occurs when when trying to align the line numbers with the lines of text. Here is a screenshot of the problem: https://www.dropbox.com/s/7sjqm4nrsqm6srh/Screen%20Shot%202012-10-11%20at%209.16.58%20PM.png For example, line 7 should be moved down since it is not at the start of a new line. I think the problem has to deal with the spacing when the lines of text wrap, but I am not sure.

So for the UITableView, I am creating the same amount of cells as there are lines of text. Then the cells are stretched so their height is the same as each line of text by using the method:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
int i = indexPath.row;
if (i == 0) {
    return 10;
}

UIFont *font = _codeView.font;

NSArray *strings = [_codeView.text componentsSeparatedByString:@"\n"];
NSString *tempString = [strings objectAtIndex:i-1];

if (([strings objectAtIndex:i-1] == @"\n") | ([[strings objectAtIndex:i-1] length] == 0) ) {
    tempString = @"hi";
}

CGSize stringSize = [tempString sizeWithFont:font constrainedToSize:CGSizeMake(_codeView.bounds.size.width, 9999) lineBreakMode:NSLineBreakByWordWrapping];
CGFloat height = stringSize.height;

return height;
}

The _codeView is the UITextView that I am using to display the code. The UITableView that displays the line numbers also has one blank cell at the top so I can align first cell with a line number with the first line of text.

I have tried multiple ways of playing with the spacing, but none of them seem to fix the problem. Any help would be greatly appreciated.

Upvotes: 2

Views: 827

Answers (2)

rmaddy
rmaddy

Reputation: 318934

I believe the problem is with the size you pass to sizeWithFont. You are setting the width to the textView's width. This will actually be a little too wide. The text view actually has a little bit of a margin. Try subtracting a few points from the width. Also, you are dealing with attributed text, not plain strings. You should look at the methods for calculating the height of an NSAttributedString.

One last thing in the code you posted. Your are splitting the _codeView.text on every call to heightForRowAtIndexPath:. That's bad. You should do this once and save off the strings. This method is called a lot. That is a lot of redundant string splits.

Upvotes: 1

tyler53
tyler53

Reputation: 429

I'm a little confused as to what you are asking.

Are you saying that you have text, and then a tableview next to it and you are trying to line the two up?

Upvotes: 0

Related Questions