UITableViewCell с динамической высотой iOS

Я реализовал TableView с CustomCell в своем приложении,

Мне нужна динамическая высота моего UITableViewCell в соответствии с длиной текста в UITableViewCell,

вот снимок Customcell

: а вот снимок моего UITableView : фрагмент кода для heightForRowAtIndexPath

#define FONT_SIZE 14.0f
#define CELL_CONTENT_WIDTH 320.0f
#define CELL_CONTENT_MARGIN 10.0f

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    NSString *text = [DescArr objectAtIndex:[indexPath row]];
    CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
    CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
    CGFloat height = MAX(size.height, 100.0);
    return height; 
}

Как вы можете видеть на втором изображении, высота ячейки фиксирована, она не меняется в зависимости от размера текста (содержимого).

Где я делаю ошибку? Как я могу сделать метку или ячейку, чтобы обновить ее размер в соответствии с ее содержимым/текстом?


person Krunal    schedule 30.08.2013    source источник
comment
Изображения отсутствуют?? :)   -  person NHS    schedule 30.08.2013
comment
Ваш фрагмент кода для расчета высоты выглядит правильно, правильно ли вы настроили делегата для табличного представления? также попробуйте записать размер: NSLog(@"Hieght: %f", height); и посмотреть, правильная ли высота.   -  person rckoenes    schedule 30.08.2013
comment
да, я правильно подключил делегата, и мой журнал показывает разную высоту 54.0, 36.0, 18.0   -  person Krunal    schedule 30.08.2013
comment
CGFloat height = MAX(size.height, 100.0); должно быть от 100 до 55 или высота ячейки по умолчанию.   -  person SachinVsSachin    schedule 30.08.2013
comment
@Sachin: ваше предложение верно после изменения высоты ячейки на 55, но метки не отображаются в центре. когда я регистрирую высоту своей ячейки в cellForRowAtIndexPath NSLog(@cell.frame.size.height=%f,cell.frame.size.height); он показывает высоту как 100 во всех ячейках   -  person Krunal    schedule 30.08.2013
comment
self.tableView.rowHeight = UITableViewAutomaticDimension; self.tableView.estimatedRowHeight = (ваша высота строки); эти 2 строки кода помогут вам установить RowHeight автоматически в зависимости от содержимого строки.   -  person RashmiG    schedule 12.03.2016
comment
Вот пример кода в swift 2.3 github.com/dpakthakur/DynamicCellHeight   -  person Deepak Thakur    schedule 17.12.2016
comment
Вы создали класс для своей пользовательской ячейки, наследуя UITableViewCell? У меня была такая же проблема, когда я создал пользовательскую ячейку UITableViewCell и связал этот класс с моим представлением в раскадровке, это сработало для меня.   -  person Nuzhat Zari    schedule 29.01.2017


Ответы (12)


Следующий код работал нормально для меня. Попробуйте с этим

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

    CGFloat lRetval = 10;
    CGSize maximumLabelSize = CGSizeMake(231, FLT_MAX);
    CGSize expectedLabelSize;


    CGFloat numberoflines = [thirdcellText length]/17.0;

    if (indexPath.section == 0) {
        expectedLabelSize = [firstcellText sizeWithFont:[UIFont systemFontOfSize:16.0]
                                      constrainedToSize:maximumLabelSize
                                          lineBreakMode:NSLineBreakByWordWrapping];
        lRetval = expectedLabelSize.height;
    }
    else if(indexPath.section == 1)
    {
        expectedLabelSize = [secondcellText sizeWithFont:[UIFont systemFontOfSize:16.0]
                                       constrainedToSize:maximumLabelSize
                                           lineBreakMode:NSLineBreakByWordWrapping];
        lRetval = expectedLabelSize.height;
    }
    else if (indexPath.section == 2)
    {
        expectedLabelSize = [thirdcellText sizeWithFont:[UIFont systemFontOfSize:16.0]
                                       constrainedToSize:CGSizeMake(231, numberoflines*17.0)
                                           lineBreakMode:NSLineBreakByWordWrapping];
        lRetval = expectedLabelSize.height-128.0;
    }

    UIImage *factoryImage = [UIImage imageNamed:NSLocalizedString(@"barcode_factory_reset.png", @"")];

    CGFloat height = factoryImage.size.height;

    if (lRetval < height) {
        lRetval = height+15.0;
    }

    return lRetval;
}

Попробуйте добавить следующий код в метод автоматической разметки класса customcell.

textview.frame = frame;
CGRect frame1 = textview.frame;
frame1.size.height = textview.contentSize.height-2;
textview.frame = frame1;


textview.contentSize = CGSizeMake(textview.frame.size.width, textview.frame.size.height);

labelPtr.frame = CGRectMake(CGRectGetMinX(imageView.frame)+CGRectGetMaxX(imageView.frame)+5.0, textview.frame.size.height+10.0, 140, 16.0);
[labelPtr setNeedsDisplayInRect:labelPtr.frame];

Попробуйте установить свойства метки, как показано ниже.

labelPtr = [[UILabel alloc] initWithFrame:CGRectZero];
labelPtr.backgroundColor =[UIColor clearColor];
[labelPtr setNeedsLayout];
[labelPtr setNeedsDisplay];
[self.contentView addSubview:labelPtr];
person NHS    schedule 30.08.2013
comment
Не беспокойтесь о ThirdcellText, это nsstring с инициализацией текста. - person NHS; 30.08.2013
comment
где инициализировать этот файл ThirdcellText? - person Krunal; 30.08.2013
comment
если у вас есть текст, для которого необходимо рассчитать высоту, вы можете получить и назначить его для ThirdcellText. вы можете назначить текст только в методе heightforrowatindexpath:. - person NHS; 30.08.2013
comment
если у вас есть текстовое представление для текста, который вы добавляете, приведенный выше код будет полезен. - person NHS; 30.08.2013
comment
Я использую Label, а не TextView - person Krunal; 30.08.2013
comment
давайте продолжим это обсуждение в чате - person NHS; 30.08.2013
comment
[firstcellText sizeWithFont:[UIFont systemFontOfSize:16.0] constrainedToSize:maximumLabelSize lineBreakMode:NSLineBreakByWordWrapping]; Этот метод кажется устаревшим. Подпишитесь на stackoverflow.com/a/22742610/3021582. - person Taranmeet Singh; 15.07.2014

Пожалуйста, посмотрите ЗДЕСЬ - Динамический Учебное пособие по высоте ячейки табличного представления и автоматической компоновке.

Что вам нужно:

  • установите необходимое ограничение на элементы в ячейке (убедитесь, что все сделано правильно, если нет - вы можете получить много проблем). Также убедитесь, что вы установили IntrinsicSize в значение PlaceHolder.

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

  • добавить несколько методов расчета размера ячейки

Методы:

//this will calculate required height for your cell
-(CGFloat)heightForBasicCellAtIndexPath:(NSIndexPath *)indexPath {
      static UIYourClassCellName *sizingCell = nil;
      //create just once per programm launching
      static dispatch_once_t onceToken;
      dispatch_once(&onceToken, ^{
      sizingCell = [self.tableView dequeueReusableCellWithIdentifier:@"identifierOfCell"];
});
  [self configureBasicCell:sizingCell atIndexPath:indexPath];
  return [self calculateHeightForConfiguredSizingCell:sizingCell];
}
//this method will calculate required height of cell
- (CGFloat)calculateHeightForConfiguredSizingCell:(UITableViewCell *)sizingCell {
      [sizingCell setNeedsLayout];
      [sizingCell layoutIfNeeded];
      CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
      return size.height;
}

И позвони

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  return [self heightForBasicCellAtIndexPath:indexPath];
}

Конфигурация ячейки

- (void)configureBasicCell:(RWBasicCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    //make some configuration for your cell
}

После всей операции я получил следующее (текст внутри ячейки только как заполнитель):

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

person hbk    schedule 07.09.2014
comment
Спасибо, это лучшее решение на сегодняшний день! - person Stornu2; 08.03.2016
comment
Вот пример кода в swift 2.3 github.com/dpakthakur/DynamicCellHeight - person Deepak Thakur; 17.12.2016

Давно ищу, как правильно определить высоту ячейки, - похоже - это лучшее решение,boundingRectWithSize и constrainedToSize часто неправильно рассчитывают высоту текста, нужно создать UILabel, чем использовать функцию sizeThatFits, см. ниже

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

    UILabel  * label = [[UILabel alloc] initWithFrame:CGRectMake(8, 5, celllabelWidth, 9999)];
    label.numberOfLines=0;
    label.font = [UIFont fontWithName:fontName size:textSize];
    label.text = @"celllabelTextHere";

    CGSize maximumLabelSize = CGSizeMake(celllabelWidth, 9999);
    CGSize expectedSize = [label sizeThatFits:maximumLabelSize];
    return expectedSize.height;
}
person user2154220    schedule 30.03.2014

Я видел много решений, но все они были неправильными или незавершенными. Вы можете решить все проблемы с помощью 5 строк в viewDidLoad и autolayout. Это для цели C:

_tableView.delegate = self;
_tableView.dataSource = self;
self.tableView.estimatedRowHeight = 80;//the estimatedRowHeight but if is more this autoincremented with autolayout
self.tableView.rowHeight = UITableViewAutomaticDimension;
[self.tableView setNeedsLayout];
[self.tableView layoutIfNeeded];
self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0) ;

Для быстрого 2.0:

 self.tableView.estimatedRowHeight = 80
 self.tableView.rowHeight = UITableViewAutomaticDimension      
 self.tableView.setNeedsLayout()
 self.tableView.layoutIfNeeded()
 self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0)

Теперь создайте свою ячейку с помощью xib или в tableview в своей раскадровке. При этом вам больше не нужно ничего реализовывать или переопределять. (Не забудьте количество строк 0) и нижнюю метку (ограничить) понизить рейтинг «Приоритет охвата контента — по вертикали до 250»

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

Вы можете загрузить код по следующему адресу: https://github.com/jposes22/exampleTableCellCustomHeight.

Ссылки: http://candycode.io/automatically-resizing-uitableviewcells-with-dynamic-text-height-using-auto-layout/

person Jose Pose S    schedule 07.02.2016
comment
Я работаю с быстрым, и ваше решение отлично работает на устройстве, поддерживающем ios 9.0. Однако при запуске на устройстве с ios7.1 ячейки становятся невидимыми. Не могли бы вы, @Jose Pose S, помочь мне. - person Cloy; 02.03.2016
comment
Мне очень жаль, я не могу помочь вам с iOS 7 :(, потому что с iOS 8 Autolayout был изменен. Вы можете использовать это с Objective-C или swift, но с iOS 8 или более поздней версии. - person Jose Pose S; 03.03.2016
comment
Вот пример кода в swift 2.3 github.com/dpakthakur/DynamicCellHeight - person Deepak Thakur; 17.12.2016
comment
Код одинаков для всех версий Swift и iOS 8 и выше. - person Jose Pose S; 25.01.2017

Теперь это очень просто
Используйте следующие шаги

  1. Установите ограничение на свою метку (при использовании пользовательской ячейки)
  2. Количество строк должно быть 0
  3. Настройте несколько свойств UITableView

self.tableView.estimatedRowHeight = 100.0;
self.tableView.rowHeight = UITableViewAutomaticDimension;

Наслаждайтесь :)
Более подробную информацию вы можете найти
www.raywenderlich.com
stackoverflow.com

person Tarun Seera    schedule 24.02.2016
comment
Вот пример кода в swift 2.3 github.com/dpakthakur/DynamicCellHeight - person Deepak Thakur; 17.12.2016

Не могли бы вы попробовать это;

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
     int topPadding = cell.yourLabel.frame.origin.x;
     int bottomPadding = cell.frame.size.heigth-(topPadding+cell.yourLabel.frame.size.height);
     NSString *text = [DescArr objectAtIndex:[indexPath row]];
     CGSize maximumSize = CGSizeMake(cell.yourLabel.frame.size.width, 9999);
     CGSize expectedSize = [text sizeWithFont:yourCell.yourLabel.font constrainedToSize:maximumSize lineBreakMode:yourCell.yourLabel.lineBreakMode];

     return topPadding+expectedSize.height+bottomPadding;
}
person Engnyl    schedule 30.08.2013
comment
Тексты ячеек переопределяются - person Krunal; 30.08.2013
comment
В .xib выберите метку, размер которой изменяется динамически, и в инспекторе файлов выберите все для автоматического изменения размера. - person Engnyl; 30.08.2013

Перейдите по этой ссылке, которую вы используете Autolayout< /а>

иначе вы можете использовать подход ниже

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {


NewsVCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

if (cell == nil)
{

    cell = [[NewsVCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];

}

cell.titleCell.numberOfLines = 0;
cell.descriptionCell.numberOfLines = 0;

cell.titleCell.font = [UIFont systemFontOfSize:12.0f];
cell.descriptionCell.font = [UIFont systemFontOfSize:12.0f];

cell.descriptionCell.textColor = [UIColor lightGrayColor];


CGSize maximumLabelSize;

if([UIDevice currentDevice].userInterfaceIdiom==UIUserInterfaceIdiomPad || [[[UIDevice currentDevice] model] isEqualToString:@"iPad Simulator"])
{
    maximumLabelSize = CGSizeMake(768, 10000);

}
else
{
    maximumLabelSize = CGSizeMake(270, 10000);

}

NSString *newsTitle =  [[feeds objectAtIndex:indexPath.row] objectForKey: @"title"];

NSString *descriptionsText = [[feeds objectAtIndex:indexPath.row] objectForKey: @"description"];


CGSize expectedTitleLabelSize = [newsTitle sizeWithFont: cell.titleCell.font constrainedToSize:maximumLabelSize lineBreakMode:cell.titleCell.lineBreakMode];

CGSize expectedDescriptionLabelSize = [descriptionsText sizeWithFont:cell.descriptionCell.font constrainedToSize:maximumLabelSize lineBreakMode:cell.descriptionCell.lineBreakMode];

NSLog(@"cellForRowAtIndexPath :indexpath.row %d: height expectedTitleLabelSize:%f , indexpath.row height expectedDescriptionLabelSize:%f",indexPath.row,expectedTitleLabelSize.height,expectedDescriptionLabelSize.height);



if (newsTitle.length > 0)
{

    cell.titleCell.frame = CGRectMake(20.0f, 10.0f, 270.0f ,expectedTitleLabelSize.height+20.0f);

}
else
{
     cell.titleCell.frame = CGRectMake(20.0f, 10.0f, 270.0f ,expectedTitleLabelSize.height-20.0f);
}


if (descriptionText.length > 0)
{
    cell.descriptionCell.frame =  CGRectMake(20.0f, 10.0f + cell.titleCell.frame.size.height, 270.0f, expectedDescriptionLabelSize.height+20.0f);

}
else
{
    cell.descriptionCell.frame =  CGRectMake(20.0f, cell.titleCell.frame.size.height, 270.0f, 0.0f);

}


  cell.descriptionCell.frame =  CGRectMake(20.0f, 10.0f + cell.titleCell.frame.size.height, 270.0f, expectedDescriptionLabelSize.height+20.0f);

cell.titleCell.text = newsTitle;
cell.descriptionCell.text = descriptionsText;

NSLog(@"indexpath.row %d :title %@ ",indexPath.row,newsTitle);

NSLog(@"indexpath.row %d :description %@",indexPath.row,descriptionsText);

return cell;

 }

метка прагмы — UITableViewDelegate

   - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
 {
float totalHeight = 0.0f;

UILabel *labelTitle;


CGSize maximumLabelSize;


if([UIDevice currentDevice].userInterfaceIdiom==UIUserInterfaceIdiomPad || [[[UIDevice currentDevice] model] isEqualToString:@"iPad Simulator"])
{
    labelTitle = [[UILabel alloc]initWithFrame:CGRectMake(0.0f, 0.0f, 692.0f, 20.0f)];  // iPad
    maximumLabelSize = CGSizeMake(768.0f, 10000.0f);

}
else
{
    labelTitle = [[UILabel alloc]initWithFrame:CGRectMake(0.0f, 0.0f, 270.0f, 20.0f)];
    maximumLabelSize = CGSizeMake(270.0f, 10000.0f);

}



labelTitle.font = [UIFont systemFontOfSize:12.0f];


NSString *newsTitle;
NSString *newsDescription;

  //  cell.titleCell.text = [[feeds objectAtIndex:indexPath.row] objectForKey: @"title"];
  //   cell.descriptionCell.text = [[feeds objectAtIndex:indexPath.row] objectForKey: @"description"];



    newsTitle = [[feeds objectAtIndex:indexPath.row] objectForKey: @"title"];

    newsDescription = [[feeds objectAtIndex:indexPath.row] objectForKey: @"description"];

NSLog(@"indexpath.row %d :newsDescription.length %d",indexPath.row,newsDescription.length);
CGSize expectedTitleLabelSize;
CGSize expectedDescriptionLabelSize;


if (newsTitle.length > 0)
{
    expectedTitleLabelSize = [newsTitle sizeWithFont:labelTitle.font constrainedToSize:maximumLabelSize lineBreakMode:labelTitle.lineBreakMode];
    totalHeight = totalHeight + 20.0f;
}
else
{
    expectedTitleLabelSize = CGSizeMake(0.0f, 0.0f);
    totalHeight = -20.0f;
}

if (newsDescription.length > 0)
{
    expectedDescriptionLabelSize = [newsDescription sizeWithFont:labelTitle.font constrainedToSize:maximumLabelSize lineBreakMode:labelTitle.lineBreakMode];
    totalHeight = totalHeight + 20.0f;

}
else
{
    expectedDescriptionLabelSize = CGSizeMake(0.0f, 0.0f);
    totalHeight = -20.0f;
}


//  NSLog(@"question: %f title:%f",expectedQuestionLabelSize.height,expectedTitleLabelSize.height);

totalHeight = expectedDescriptionLabelSize.height + expectedTitleLabelSize.height + 30.0f+20.0f;




return totalHeight;

 }
person bhavya kothari    schedule 03.02.2014

Если вы хотите ограничить максимальную высоту до 100 pt, вы должны использовать MIN вместо MAX:

CGFloat height = fmin(size.height, 100.0);
person Nikolai Ruhe    schedule 03.02.2014

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

  • Назначение и реализация tableview dataSource и делегата
  • Назначьте UITableViewAutomaticDimension для rowHeight и предполагаемойRowHeight
  • Реализовать методы делегата/источника данных (т.е. heightForRowAt и вернуть ему значение 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.
  • Необязательно: установите минимальную высоту для метки, если вы хотите, чтобы метка покрывала минимальную площадь по вертикали, даже если данных нет.

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

person Krunal    schedule 12.10.2017

Мне нужна была динамическая высота ячейки представления таблицы в зависимости от количества текста, который будет отображаться в этой ячейке. Я решил это следующим образом:

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

            if ([self.conditionsDataArray count]>0)
            {
                Conditions *condition =[self.conditionsDataArray objectAtIndex:indexPath.row];
                int height;
                UITextView *textview = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 236, 0)];   //you can set your frame according to your need
                textview.text  = condition.comment;
                textview.autoresizingMask = UIViewAutoresizingFlexibleHeight;
                [tableView addSubview:textview];
                textview.hidden = YES;
                height = textview.contentSize.height;
                NSLog(@"TEXT VIEW HEIGHT %f", textview.contentSize.height);
                [textview removeFromSuperview];
                [textview release];
                return height;
       }
       return 55;  //Default height, if data is in loading state
}

Обратите внимание, что Text View был добавлен как Subview, а затем сделан скрытым, поэтому убедитесь, что вы добавили его как SubView, иначе его высота не будет учитываться.

person Jamal Zafar    schedule 30.08.2013
comment
Ууууу. Не делай этого. Этот метод должен быть чертовски быстрым и не должен содержать никаких модификаций иерархии представлений. - person allprog; 30.08.2013
comment
@allprog: никаких компромиссов в производительности, я успешно использовал этот метод, и он работает без сбоев в моем приложении. - person Jamal Zafar; 30.08.2013
comment
Если ты так говоришь. Я еще не пробовал, но вы меня заинтересовали. UITableView, похоже, не работает в этом отношении, поскольку он запрашивает высоту, а затем содержимое. Я уверен, что это связано с некоторой оптимизацией, но в данном случае требуется расчет дважды. - person allprog; 30.08.2013
comment
Вот пример кода в swift 2.3 github.com/dpakthakur/DynamicCellHeight - person Deepak Thakur; 17.12.2016

Я только что написал об этой проблеме и подходе, который я в итоге выбрал. Вы можете прочитать об этом здесь: Динамическая высота ячейки UITableView на основе содержимого

По сути, я создал подкласс UITableView, который обрабатывает все это как для ячеек по умолчанию, так и для пользовательских ячеек. Это, вероятно, нуждается в настройке, но я использовал его как есть с хорошим результатом.

Вы можете получить код здесь: https://github.com/danielsaidi/DSTableViewWithDynamicHeight

Надеюсь, это поможет (... и если это не помогло, я извиняюсь и хотел бы услышать, почему нет)

person Daniel Saidi    schedule 20.02.2014

Попробуйте это, это сработало как шарм! для меня,

В viewDidLoad напишите этот код,

-(void)viewDidLoad 
{
[super viewDidLoad];
 self.tableView.estimatedRowHeight = 100.0; // for example. Set your average height
 self.tableView.rowHeight = UITableViewAutomaticDimension;
}

В cellForRowAtIndexPath напишите этот код,

 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {
  static NSString *CellIdentifier = @"Cell";
  UITableViewCell *cell = [tableView 
  dequeueReusableCellWithIdentifier:CellIdentifier];
 if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] ;
  }
    cell.textLabel.numberOfLines = 0; // Set label number of line to 0
    cell.textLabel.text=[[self.arForTable objectAtIndex:indexPath.row] valueForKey:@"menu"];
    [cell.textLabel sizeToFit]; //set size to fit 
    return cell;
 }

Надеюсь, что это поможет кому-то.

person Jaywant Khedkar    schedule 05.01.2018