Ustawienie niestandardowe UITableViewCells wysokość

głosy
209

Używam niestandardowej UITableViewCell, który ma kilka etykiet, przyciski i widoki obraz ma być wyświetlany. Jest jedna etykieta w komórce, której tekst jest NSStringprzedmiot i długość łańcucha może być zmienna. Ze względu na to, że nie można ustawić stałą wysokość do komórki w UITableView„s heightForCellAtIndexmetody. Wzrost komórki w zależności od wysokości etykiety, która może być określona za pomocą NSString„S sizeWithFontmetody. Próbowałem go używać, ale wygląda na to, idę gdzieś źle. Jak to może być stałe?

Oto kod używany do inicjowania komórkę.

if (self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier])
{
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    UIImage *image = [UIImage imageNamed:@dot.png];
    imageView = [[UIImageView alloc] initWithImage:image];
    imageView.frame = CGRectMake(45.0,10.0,10,10);

    headingTxt = [[UILabel alloc] initWithFrame:   CGRectMake(60.0,0.0,150.0,post_hdg_ht)];
    [headingTxt setContentMode: UIViewContentModeCenter];
    headingTxt.text = postData.user_f_name;
    headingTxt.font = [UIFont boldSystemFontOfSize:13];
    headingTxt.textAlignment = UITextAlignmentLeft;
    headingTxt.textColor = [UIColor blackColor];

    dateTxt = [[UILabel alloc] initWithFrame:CGRectMake(55.0,23.0,150.0,post_date_ht)];
    dateTxt.text = postData.created_dtm;
    dateTxt.font = [UIFont italicSystemFontOfSize:11];
    dateTxt.textAlignment = UITextAlignmentLeft;
    dateTxt.textColor = [UIColor grayColor];

    NSString * text1 = postData.post_body;
    NSLog(@text length = %d,[text1 length]);
    CGRect bounds = [UIScreen mainScreen].bounds;
    CGFloat tableViewWidth;
    CGFloat width = 0;
    tableViewWidth = bounds.size.width/2;
    width = tableViewWidth - 40; //fudge factor
    //CGSize textSize = {width, 20000.0f}; //width and height of text area
    CGSize textSize = {245.0, 20000.0f}; //width and height of text area
    CGSize size1 = [text1 sizeWithFont:[UIFont systemFontOfSize:11.0f]
                        constrainedToSize:textSize lineBreakMode:UILineBreakModeWordWrap];

    CGFloat ht = MAX(size1.height, 28);
    textView = [[UILabel alloc] initWithFrame:CGRectMake(55.0,42.0,245.0,ht)];
    textView.text = postData.post_body;
    textView.font = [UIFont systemFontOfSize:11];
    textView.textAlignment = UITextAlignmentLeft;
    textView.textColor = [UIColor blackColor];
    textView.lineBreakMode = UILineBreakModeWordWrap;
    textView.numberOfLines = 3;
    textView.autoresizesSubviews = YES;

    [self.contentView addSubview:imageView];
    [self.contentView addSubview:textView];
    [self.contentView addSubview:webView];
    [self.contentView addSubview:dateTxt];
    [self.contentView addSubview:headingTxt];
    [self.contentView sizeToFit];

    [imageView release];
    [textView release];
    [webView release];
    [dateTxt release];
    [headingTxt release];
}

To jest etykieta, której wysokość i szerokość idą źle:

textView = [[UILabel alloc] initWithFrame:CGRectMake(55.0,42.0,245.0,ht)];
Utwórz 30/01/2009 o 06:27
źródło użytkownik
W innych językach...                            


9 odpowiedzi

głosy
483

Twoja UITableViewDelegatepowinny wdrożyćtableView:heightForRowAtIndexPath:

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

Prawdopodobnie będzie chciał użyć NSString„s sizeWithFont:constrainedToSize:lineBreakMode:sposób obliczyć wysokość wiersza zamiast po prostu wykonując jakąś głupią matematyki na indexPath :)

Odpowiedział 30/01/2009 o 23:46
źródło użytkownik

głosy
121

Jeśli wszystkie wiersze są na tej samej wysokości, po prostu ustawić rowHeightwłaściwość UITableView zamiast wdrażającego heightForRowAtIndexPath. Jabłko Docs:

Są to wpływ na wydajność do korzystania Tableview: heightForRowAtIndexPath: Zamiast rowHeight. Za każdym razem wyświetlany jest widok tabeli, wywołuje Tableview: heightForRowAtIndexPath: na delegata do każdego z jego wierszy, które mogą doprowadzić do znacznego problemu wydajności z widokiem stołowe posiadające dużą liczbę wierszy (około 1000 lub więcej).

Odpowiedział 19/01/2011 o 00:59
źródło użytkownik

głosy
22

w zwyczaju UITableViewCell -controller dodać ten

-(void)layoutSubviews {  

    CGRect newCellSubViewsFrame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    CGRect newCellViewFrame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, self.frame.size.height);

    self.contentView.frame = self.contentView.bounds = self.backgroundView.frame = self.accessoryView.frame = newCellSubViewsFrame;
    self.frame = newCellViewFrame;

    [super layoutSubviews];
}

W UITableView -controller dodać ten

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [indexPath row] * 1.5; // your dynamic height...
}
Odpowiedział 19/01/2010 o 14:26
źródło użytkownik

głosy
17
#define FONT_SIZE 14.0f
#define CELL_CONTENT_WIDTH 300.0f
#define CELL_CONTENT_MARGIN 10.0f

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath      *)indexPath;
{
   /// Here you can set also height according to your section and row
   if(indexPath.section==0 && indexPath.row==0)
   {
     text=@"pass here your dynamic data";

     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, 44.0f);

     return height + (CELL_CONTENT_MARGIN * 2);
   }
   else
   {
      return 44;
   }
}

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    UILabel *label = nil;

    cell = [tv dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil)
    {
       cell = [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"Cell"];
    }
    ********Here you can set also height according to your section and row*********
    if(indexPath.section==0 && indexPath.row==0)
    {
        label = [[UILabel alloc] initWithFrame:CGRectZero];
        [label setLineBreakMode:UILineBreakModeWordWrap];
        [label setMinimumFontSize:FONT_SIZE];
        [label setNumberOfLines:0];
        label.backgroundColor=[UIColor clearColor];
        [label setFont:[UIFont systemFontOfSize:FONT_SIZE]];
        [label setTag:1];

        // NSString *text1 =[NSString stringWithFormat:@"%@",text];

        CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);

        CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];

        if (!label)
        label = (UILabel*)[cell viewWithTag:1];


        label.text=[NSString stringWithFormat:@"%@",text];
        [label setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH          - (CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];
        [cell.contentView addSubview:label];
    }
return cell;
}
Odpowiedział 19/09/2012 o 10:30
źródło użytkownik

głosy
8
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    CGSize constraintSize = {245.0, 20000}
    CGSize neededSize = [ yourText sizeWithFont:[UIfont systemFontOfSize:14.0f] constrainedToSize:constraintSize  lineBreakMode:UILineBreakModeCharacterWrap]
if ( neededSize.height <= 18) 

   return 45
else return neededSize.height + 45 
//18 is the size of your text with the requested font (systemFontOfSize 14). if you change fonts you have a different number to use  
// 45 is what is required to have a nice cell as the neededSize.height is the "text"'s height only
//not the cell.

}
Odpowiedział 18/11/2012 o 17:20
źródło użytkownik

głosy
5

Widziałem wiele rozwiązań, ale wszystko było złe lub uncomplet. można rozwiązać wszystkie problemy z 5 linii w viewDidLoad i autoLayout. To dla objetive 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) ;

Dla szybkiej 2,0:

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

Teraz utworzyć komórkę z xib lub w tableview w Twoim Planie Mając to ty nic nie trzeba wdrożyć bardziej lub nadpisać. (Don zapomnieć liczba linii os 0) i dolny (ograniczenie dla etykietę) downgrade „przytulenia zawartość Priority - Pionowy 250”

wprowadzić opis obrazu tutaj wprowadzić opis obrazu tutaj

Można donwload kod w następnym URL: https://github.com/jposes22/exampleTableCellCustomHeight

Referencje: http://candycode.io/automatically-resizing-uitableviewcells-with-dynamic-text-height-using-auto-layout/

Odpowiedział 26/01/2016 o 19:58
źródło użytkownik

głosy
5

Dzięki dla wszystkich stanowisk w tym temacie, istnieje kilka naprawdę pomocne sposoby, aby dostosować rowHeight o UITableViewCell.

Oto zestawienie niektórych pojęć z każdego innego, co naprawdę pomaga przy budowaniu dla iPhone i iPad. Można również uzyskać dostęp do różnych sekcji i ustawić je według różnych rozmiarach poglądów.

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

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
    int cellHeight = 0;

    if ([indexPath section] == 0) 
    {
        cellHeight = 16;
        settingsTable.rowHeight = cellHeight;
    }
    else if ([indexPath section] == 1)
    {
        cellHeight = 20;
        settingsTable.rowHeight = cellHeight;
    }

    return cellHeight;
}
else
{
    int cellHeight = 0;

    if ([indexPath section] == 0) 
    {
        cellHeight = 24;
        settingsTable.rowHeight = cellHeight;
    }
    else if ([indexPath section] == 1)
    {
        cellHeight = 40;
        settingsTable.rowHeight = cellHeight;
    }

    return cellHeight;
}
return 0;
} 
Odpowiedział 22/03/2012 o 21:02
źródło użytkownik

głosy
3

Aby mieć dynamiczny wzrost komórek jako tekst wzrasta Label, trzeba najpierw obliczyć wysokość, że tekst będzie zastosowanie w -heightForRowAtIndexPathmetodzie delegata i odesłać go z dodanymi wysokościach innych lables, obrazów (max wysokość tekstu + wysokości inny statyczny komponentu) i używać tej samej wysokości w tworzeniu komórek.

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

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

    if (indexPath.row == 2) {  // the cell you want to be dynamic

        NSString *text = dynamic text for your label;

        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, 44.0f);

        return height + (CELL_CONTENT_MARGIN * 2);
    }
    else {
        return 44; // return normal cell height
    }
}

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

    static NSString *CellIdentifier = @"Cell";

    UILabel *label;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] ;
    }

    label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 280, 34)];

    [label setNumberOfLines:2];

    label.backgroundColor = [UIColor clearColor];

    [label setFont:[UIFont systemFontOfSize:FONT_SIZE]];

    label.adjustsFontSizeToFitWidth = NO;

    [[cell contentView] addSubview:label];


    NSString *text = dynamic text fro your label;

    [label setText:text];

    if (indexPath.row == 2) {// the cell which needs to be dynamic 

        [label setNumberOfLines:0];

        CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);

        CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];

        [label setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];

    }
    return  cell;
}
Odpowiedział 01/08/2012 o 12:07
źródło użytkownik

głosy
2

Aby ustawić automatyczne wymiar wysokości wiersza i szacunkowa wysokość wiersza, zapewniają następujące kroki, aby, autowymiarowania skuteczne dla układu wysokość komórki / wiersza.

  • Przypisywanie i wdrożenie Tableview DataSource i delegować
  • Przypisać UITableViewAutomaticDimensiondo rowHeight & estimatedRowHeight
  • Wdrożenie metod delegata / DataSource (IE heightForRowAti zwracają wartość UITableViewAutomaticDimensiondo niego)

-

Cel 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;
}

Szybki:

@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
    table.rowHeight = UITableViewAutomaticDimension
    table.estimatedRowHeight = UITableViewAutomaticDimension
}



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

Na przykład etykiety w UITableViewCell

  • Ustalonej liczby linii = 0 (i tryb końca linii = obciąć ogon)
  • Ustaw wszystkie ograniczenia (górny, dolny, prawy lewy) w odniesieniu do jego pojemnika superview / komórek.
  • Opcjonalnie : Ustaw minimalną wysokość na etykiecie, jeśli chcesz minimalną powierzchnię pionową objętej etykiety, nawet jeśli nie ma żadnych danych.

wprowadzić opis obrazu tutaj

Uwaga : Jeśli masz więcej niż jedno etykiet (UIElements) z dynamicznym długości, która powinna być dostosowana do jego wielkości zawartości: Dostosuj „przytulenia Treść i kompresji Odporność Priority` do etykiet, które chcesz rozwinąć / skompresować o wyższym priorytecie.

Tu, w tym przykładzie mogę ustawić niską tulenie i wysokiej odporności na ściskanie priorytet, który prowadzi do określania bardziej priorytet / znaczenie dla treści drugiego (żółty) etykiety.

wprowadzić opis obrazu tutaj

Odpowiedział 02/02/2018 o 15:20
źródło użytkownik

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more