как отрегулировать высоту ячейки при загрузке из пользовательских классов ячеек tableview?

У меня есть приложение, в котором я добавляю 2 типа ячеек в двух дизайнах. Поэтому я использую пользовательские UITableViewCell классы объектов. Но моя проблема в том, что я использую текстовое представление в этих ячейках. Мне нужно настроить высоту строки в соответствии с размером ее содержимого. Вот как выглядит мой код:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier1 = @"CellIdentifier";
    static NSString *CellIdentifier2 = @"Cell";
        
    if(messagesarray==nil||[messagesarray count]==0)
    {
        
    }
    else
    {
        NSMutableDictionary *dicttable=[messagesarray objectAtIndex:indexPath.row];
        NSString *head=[dicttable objectForKey:@"gfgfg"];
        NSString *head1=[dicttable objectForKey:@"gfgfgf"];
        if([type isEqualToString:@"m"])    
        {
            if([head isEqualToString:@"NA"])
            {
             
                CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
                if (cell == nil)
                {
                    cell = [[[CustomCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier1] autorelease];
                    cell.backgroundView = [ [[UIImageView alloc] initWithImage:[ [UIImage imageNamed:@"white_top_portion.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ]autorelease];
                }
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.nameLabel.text=head;
                cell.msg.text=head1;
                [cell.button addTarget:self action:@selector(callAction:) forControlEvents:UIControlEventTouchUpInside];     
              
                if(icon!=nil)
                {
                    if(![[ImageCache sharedImageCache] hasImageWithKey:icon])
                    {
                        cell.myImageView.image = [UIImage imageNamed:@"fggtgf.png"];
                        NSArray *myArray = [NSArray arrayWithObjects:cell.myImageView,icon,@"fgfgfg.png",[NSNumber numberWithBool:NO],nil];
                        AppDelegate *appDelegate = (AppDelegate  *)[[UIApplication sharedApplication] delegate];
                        [appDelegate performSelectorInBackground:@selector(updateImageViewInBackground:) withObject:myArray];   
                    }
                    else 
                    {
                        cell.myImageView.image = [[ImageCache sharedImageCache] getImagefromCacheOrUrl:icon];
                    }
                }
                else
                {
                    cell.myImageView.image = [UIImage imageNamed:@"fgfgfg.png"];  
                  
                } 
         
                cell.label.text=sub;   
                return cell;
            }
            else
            {
                Customcellwithimage *cell = (Customcellwithimage *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
             
                if (cell == nil)
                {
                    cell = [[[Customcellwithimage alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier2] autorelease];
                    cell.backgroundView = [ [[UIImageView alloc] initWithImage:[ [UIImage imageNamed:@"white_deal_bg.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ]autorelease];
                }
             
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.datelabel1.text=subtitle;
                cell.nameLabel1.text=head;
                cell.msg1.text=head1;
                if(icon!=nil)
                {
                    if(![[ImageCache sharedImageCache] hasImageWithKey:icon])
                    {
                        cell.myImageView1.image = [UIImage imageNamed:@"fgfgfgf.png"];
                        NSArray *myArray = [NSArray arrayWithObjects:cell.myImageView1,icon,@"fgfgfgf.png",[NSNumber numberWithBool:NO],nil];
                        MFAppDelegate *appDelegate = (MFAppDelegate  *)[[UIApplication sharedApplication] delegate];
                        [appDelegate performSelectorInBackground:@selector(updateImageViewInBackground:) withObject:myArray];   
                       
                    }
                    else 
                    {
                        cell.myImageView1.image = [[ImageCache sharedImageCache] getImagefromCacheOrUrl:icon];
                    }
                }
                else
                {
                    cell.myImageView1.image = [UIImage imageNamed:@"fgfgfgf.png"];  
                } 
              
                cell.cellview1.image=[UIImage imageNamed:@"vf.png"];
                cell.label1.text=sub;
                [cell.button1 addTarget:self action:@selector(callAction:) forControlEvents:UIControlEventTouchUpInside]; 
                cell.bannerview1.image=[UIImage imageNamed:@"vfgf.png"];
                return cell;
            }   
        }                 
    }  
}
       

Может ли кто-нибудь помочь мне в достижении высоты строки, которая отличается для разных ячеек? Мне нужно узнать высоту в - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath, и я попробовал метод, который должен будет узнать объект ячейки текущей строки. но не удалось. Может ли кто-нибудь помочь мне в правильном направлении


person hacker    schedule 12.12.2012    source источник
comment
Можете ли вы опубликовать свою реализацию - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *) - не знаю, в чем проблема.   -  person lindon fox    schedule 12.12.2012
comment
проверьте мой ответ для автоматического изменения его высоты в соответствии с содержимым в xcode"> stackoverflow.com/questions/13656857/   -  person Rajneesh071    schedule 12.12.2012


Ответы (3)


Я думаю, вы ищете - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath - Здесь вы можете рассчитать высоту для каждой отдельной строки.

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

person lindon fox    schedule 12.12.2012

Вы можете использовать этот метод для поддержки переменной высоты для вашего приложения.

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

Всякий раз, когда вы хотите установить высоту динамически, вызывайте этот метод с вашим объектом tableview.

Для получения дополнительной информации Нажмите здесь

или используйте этот метод с другими методами делегата tableview.

person iCreative    schedule 12.12.2012
comment
извините..что я знаю. нужен способ в этом конкретном случае внутри этого метода - person hacker; 12.12.2012
comment
я написал это выше.. Ну, вы можете использовать эту строку, где вы хотите изменить высоту строки: [tableView setRowHeight:‹требуемое значение в float›]; - person iCreative; 12.12.2012

Изменение размера ячейки может быть довольно сложным, особенно когда задействованы UITextViews. Я предлагаю вам просто использовать структуру табличного представления, такую ​​как Sensible TableView, где все ячейки автоматически изменяются в соответствии с содержимым. Я считаю, что у них также теперь есть бесплатная версия.

person Matt    schedule 12.12.2012