Ваша проблема, как вы уже комментарий является то, что функция heightForRowAtIndexPath
вызывается перед клетки заселяются.
Для каждой клетки, которые становятся видимым его первым называет
- высоты ПОЛУЧИТЬ эту клетку
- Заселите клетки
Таким образом, вы знаете, что
а) ваш текст не заполненный по ячейке
б) какой-либо другой текст может быть внутри, bec ause apple использует повторно используемые ячейки, поэтому UITableView может захватить некоторую ячейку (с другим текстом) и попытаться изменить ее размер, а затем заполнить ее.
В вашем случае он будет захватывать какой-либо другой текст, изменять размер ячейки до ее размера, а затем заполнять ее другим текстом, который (возможно) отличается от предыдущего текста.
Но внутри популяции клеток вы задаете текст из некоторой бизнес-логики (возможно, массив?), И вы можете получить тот же текст в этом методе.
если популяция клеток вы звоните
cell.comment.text = [self.someArray getObjectAtIndex:index.row];
вы называете это в методе heightForRowAtIndexPath
.
NSString *text = [self.someArray getObjectAtIndex:index.row];
Я вижу, что ваша правка просто позвоните:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@"text : %@", self.cell.comment.text);
NSString *text = [object objectForKey:@"comment"];;
CGFloat width = self.cell.frame.size.width;
UIFont *font = [UIFont fontWithName:@"HelveticaNeue" size:15];
NSAttributedString *attributedText =
[[NSAttributedString alloc] initWithString:text
attributes:@{NSFontAttributeName: font}];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGSize size = rect.size;
CGFloat height = ceilf(size.height);
return height;
}
Сложение:
Тел говорят, что вы хотели бы иметь клетки, как это:
-------------------------
| bla bla bla |
------------------------
| second longer text |
| over more line |
------------------------
У вас должны быть тексты bla bla
и «второй длинный текст над более строкой» где-то сохранено.
Пусть у вас есть массив размера 2.
NSArray * myTextArray = @[@"bla bla", @"second longer text over more line"];
и при наполнении клеток
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object{
static NSString *simpleTableIdentifier = @"cell";
self.cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (self.cell == nil) {
self.cell = [[CommentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
// Configure the cell
self.cell.comment.text = [myTextArray objectAtIndex:indexPath.row];
[self.cell.comment sizeToFit];
return self.cell;
}
потому что heightForRowAtIndexPath
вызывается перед cellForRowAtIndexPath
нам нужно проверить текст из бизнеса (массив) стороны и не визуальный.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@"text : %@", self.cell.comment.text); // -> this is null because cell is not populated yet.
NSString *text = [myTextArray objectAtIndex:indexPath.row]; -> this is same text as we will take when populating cell and is not random.
CGFloat width = self.cell.frame.size.width;
UIFont *font = [UIFont fontWithName:@"HelveticaNeue" size:15];
NSAttributedString *attributedText =
[[NSAttributedString alloc] initWithString:text
attributes:@{NSFontAttributeName: font}];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGSize size = rect.size;
CGFloat height = ceilf(size.height);
return height;
}
Пример:
#import "ViewController.h"
@interface ViewController()
@property NSArray * myArray;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.myArray = @[@"Some short text",@"Some longer text that take some more space throw more lines",@"bfusdbfjdsfjs fj yfsdy fgsydu fyudsfy fyudsyu fdsy fuysdyuf ydsug fyu sdgyfgsuyff ius fhs fiusdhi ufdshu uifsd ufsdh hfiuds uifdsh fsduih ufdshu hfsd ifshui"];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 3;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *text = self.myArray[indexPath.row];
CGFloat width = 300;
UIFont *font = [UIFont fontWithName:@"HelveticaNeue" size:15];
NSAttributedString *attributedText =
[[NSAttributedString alloc] initWithString:text
attributes:@{NSFontAttributeName: font}];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGSize size = rect.size;
CGFloat height = ceilf(size.height);
return height;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = @"cell";
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
// Configure the cell
cell.textLabel.text = self.myArray[indexPath.row];
cell.textLabel.numberOfLines = 0;
return cell;
}
этот пример работает.
Каково значение «текста», когда вы достигаете этой строки? – Fogmeister
Я получаю ноль. если я прокомментирую все это, без ошибок, я вижу все комментарии к моему табло, чтобы они все прошли. – durazno
Я думаю, вы сбиваете с толку, что такое self.cell. Где вы устанавливаете 'self.cell.comment.text'? – Fogmeister