AutoLayout в UITableview с динамической высотой ячейки

Для динамической высоты моей ячейки представления таблицы я беру ссылку из этой ссылки. Использование автоматического макета в UITableView для динамической ячейки макеты и переменная высота строк

Вот пользовательская ячейка со всеми ограничениями

Вот мой код источника данных tableview и методов делегата

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
  {
       return arrTemp. count;
  }

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier=@"AutoLAyoutCell";

AutoLayoutTableViewCell *cell=(AutoLayoutTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell==nil) {
    for (id currentObject in [[NSBundle mainBundle] loadNibNamed:@"AutoLayoutTableViewCell" owner:self options:nil]) {
        if ([currentObject isKindOfClass:[UITableViewCell class]]) {
            cell = (AutoLayoutTableViewCell *)currentObject;
            break;
        }
    }
}

cell.IBlblLineNo.text=[NSString stringWithFormat:@"Line:%i",indexPath.row];
cell.IBlblLineText.text=[arrTemp objectAtIndex:indexPath.row];
[cell setNeedsUpdateConstraints];
[cell updateConstraintsIfNeeded];

CGSize expectedlineLabelSize = [cell.IBlblLineText.text sizeWithFont:cell.IBlblLineText.font constrainedToSize:CGSizeMake(280, 1000) lineBreakMode:NSLineBreakByTruncatingTail];
cell.IBlblLineText.numberOfLines=expectedlineLabelSize.height/17;

CGRect frmlbl=cell.IBlblLineText.frame;
frmlbl.size.height=expectedlineLabelSize.height;
cell.IBlblLineText.frame=frmlbl;

return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

AutoLayoutTableViewCell *cell = (AutoLayoutTableViewCell *)[IBtblAutoLayoutExample cellForRowAtIndexPath:indexPath];

cell.IBlblLineNo.text=[NSString stringWithFormat:@"Line:%i",indexPath.row];
cell.IBlblLineText.text=[arrTemp objectAtIndex:indexPath.row];

[cell setNeedsUpdateConstraints];
[cell updateConstraintsIfNeeded];

CGSize expectedlineLabelSize = [cell.lineLabel.text sizeWithFont:cell.lineLabel.font constrainedToSize:CGSizeMake(280, 1000) lineBreakMode:NSLineBreakByWordWrapping];

 cell.IBlblLineText.numberOfLines=expectedlineLabelSize.height/17;
CGRect frmlbl=cell.IBlblLineText.frame;
frmlbl.size.height=expectedlineLabelSize.height;
cell.IBlblLineText.frame=frmlbl;

CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
height += 1.0f;

return height;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
     AutoLayoutTableViewCell *cell = (AutoLayoutTableViewCell *)[IBtblAutoLayoutExample cellForRowAtIndexPath:indexPath];

 CGSize expectedlineLabelSize = [cell.IBlblLineText.text sizeWithFont:cell.IBlblLineText.font constrainedToSize:CGSizeMake(280, 1000) lineBreakMode:NSLineBreakByTruncatingTail];

 return expectedlineLabelSize.height;

}

У меня есть 2 вопроса:

  1. Моя проблема в том, что я получаю ошибку EXE_BAD_EXCESS рядом с линией

    AutoLayoutTableViewCell *cell = (AutoLayoutTableViewCell *)[IBtblAutoLayoutExample cellForRowAtIndexPath:indexPath]; 
    

    в heightForRowAtIndexPath и estimatedHeightForRowAtIndexPath.

  2. Почему я должен писать текст метки как в cellForRowAtIndexPath, так и в heightForRowAtIndexPath?

Кроме того, мне не хватает чего-либо, необходимого для достижения динамической высоты ячейки?


person Pooja Shah    schedule 18.05.2014    source источник
comment
Является ли IBtblAutoLayoutExample именем вашего табличного представления?   -  person E-Riddie    schedule 18.05.2014
comment
Да, это IBOutlet для моего представления таблицы.   -  person Pooja Shah    schedule 18.05.2014
comment
Я думаю, вам не нужно реализовывать heightForRowAtIndexPath и предполагаемыйHeightForRowAtIndexPath, это может быть возможно с прямым ограничением в вашей ячейке, и вам просто нужно установить предполагаемое свойство строки и высоты строки представления таблицы.   -  person Paresh Patel    schedule 12.10.2017


Ответы (1)


Чтобы установить автоматическое измерение высоты строки и предполагаемой высоты строки, убедитесь, что следующие шаги позволяют сделать автоматическое измерение эффективным для макета высоты ячейки/строки.

  • Назначение и реализация tableview dataSource и делегата
  • Назначьте UITableViewAutomaticDimension для rowHeight и предполагаемойRowHeight
  • Реализовать методы делегата/источника данных (т.е. heightForRowAt и вернуть ему значение UITableViewAutomaticDimension)

-

Цель C:

// in ViewController.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

  @property IBOutlet UITableView * table;

@end

// in ViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];
    self.table.dataSource = self;
    self.table.delegate = self;

    self.table.rowHeight = UITableViewAutomaticDimension;
    self.table.estimatedRowHeight = UITableViewAutomaticDimension;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return UITableViewAutomaticDimension;
}

Свифт:

@IBOutlet weak var table: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Don't forget to set dataSource and delegate for table
    table.dataSource = self
    table.delegate = self

    // Set automatic dimensions for row height
    // Swift 4.2 onwards
    table.rowHeight = UITableView.automaticDimension
    table.estimatedRowHeight = UITableView.automaticDimension


    // Swift 4.1 and below
    table.rowHeight = UITableViewAutomaticDimension
    table.estimatedRowHeight = UITableViewAutomaticDimension

}



// UITableViewAutomaticDimension calculates height of label contents/text
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    // Swift 4.2 onwards
    return UITableView.automaticDimension

    // Swift 4.1 and below
    return UITableViewAutomaticDimension
}

Для экземпляра метки в UITableviewCell

  • Установить количество строк = 0 (и режим разрыва строки = обрезать конец)
  • Установите все ограничения (сверху, снизу, справа и слева) в отношении его контейнера superview/cell.
  • Необязательно: установите минимальную высоту для метки, если вы хотите, чтобы метка покрывала минимальную площадь по вертикали, даже если данных нет.

введите здесь описание изображения

Примечание. Если у вас есть более одной метки (UIElements) с динамической длиной, которая должна быть скорректирована в соответствии с размером ее содержимого: настройте «Приоритет облегания содержимого и сопротивления сжатию» для меток, которые вы хотите расширить. /compress с более высоким приоритетом.

person Krunal    schedule 16.10.2017