Jak owinąć tekst w UITableViewCell bez niestandardowej komórki

To jest na iPhone 0S 2.0. Odpowiedzi dla 2.1 też są w porządku, chociaż nie jestem świadomy żadnych różnic dotyczących tabel.

Wydaje się, że powinno być możliwe owinięcie tekstu bez tworzenia niestandardowej komórki, ponieważ UITableViewCell domyślnie zawiera UILabel. Wiem, że mogę to zrobić, jeśli stworzę niestandardową komórkę, ale nie to próbuję osiągnąć - chcę zrozumieć, dlaczego moje obecne podejście nie działa.

Doszedłem do wniosku, że etykieta jest tworzona na żądanie (od Komórka obsługuje dostęp do tekstu i obrazu, więc nie tworzy widoku danych dopóki nie jest to konieczne), więc jeśli zrobię coś takiego:

cell.text = @""; // create the label
UILabel* label = (UILabel*)[[cell.contentView subviews] objectAtIndex:0];

Potem dostaję poprawną etykietę, ale ustawienie numberOfLines na tym (i lineBreakMode) nie działa - nadal dostaję tekst w jednej linii. W UILabel jest dużo wysokości do wyświetlenia tekstu - zwracam tylko dużą wartość dla wysokości w heightForRowAtIndexPath.

Author: Vadim Kotov, 2008-09-25

9 answers

Tutaj jest prostszy sposób, i to działa dla mnie:

Wewnątrz Twojej cellForRowAtIndexPath: funkcji. Po raz pierwszy tworzysz komórkę:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0];
}

Zauważysz, że ustawiłem liczbę linii dla etykiety na 0. Pozwala to na użycie tylu linii, ile potrzebuje.

Następna część to określenie jak duża będzie twoja UITableViewCell, więc zrób to w swojej heightForRowAtIndexPath Funkcji:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellText = @"Go get some text for your cell.";
    UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:17.0];
    CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
    CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];

    return labelSize.height + 20;
}

Dodałem 20 do wysokości zwracanej komórki, ponieważ lubię mały bufor wokół mojego tekstu.

 273
Author: Tim Rupe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-19 22:17:23

Zaktualizowano odpowiedź Tima Rupe dla iOS7:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
    cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellText = @"Go get some text for your cell.";
    UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:17.0];

    NSAttributedString *attributedText =
        [[NSAttributedString alloc]
            initWithString:cellText
            attributes:@
            {
                NSFontAttributeName: cellFont
            }];
    CGRect rect = [attributedText boundingRectWithSize:CGSizeMake(tableView.bounds.size.width, CGFLOAT_MAX)
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                               context:nil];
    return rect.size.height + 20;
}
 15
Author: ddiego,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-06 21:00:32

Krótki komentarz / odpowiedź, aby nagrać moje doświadczenie, gdy miałem ten sam problem. Pomimo użycia przykładów kodu, wysokość komórki widoku tabeli dostosowywała się, ale etykieta wewnątrz komórki nadal nie dostosowywała się poprawnie - rozwiązaniem było to, że ładowałem komórkę z niestandardowego pliku NIB, co dzieje się po wysokości komórki w adjusted.

I miałem moje ustawienia wewnątrz pliku NIB, aby nie zawijać tekstu, a tylko 1 linia dla etykiety; ustawienia pliku NIB były nadrzędne ustawienia poprawiłem w kodzie.

Lekcją, którą wziąłem było upewnienie się, że zawsze pamiętać, jaki jest stan przedmiotów w każdym momencie w czasie - mogą nie zostały jeszcze stworzone! ... to ktoś z linii.

 3
Author: Richard Le Mesurier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-02-14 08:31:09

Jeśli mamy dodać tylko tekst w komórce UITableView, potrzebujemy tylko dwóch delegatów do pracy (nie trzeba dodawać dodatkowych UILabels)

1) cellForRowAtIndexPath

2) heightForRowAtIndexPath

To rozwiązanie zadziałało dla mnie:-

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

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

    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:16];
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.numberOfLines = 0;

    [cell setSelectionStyle:UITableViewCellSelectionStyleGray]; 
    cell.textLabel.text = [mutArr objectAtIndex:indexPath.section];
    NSLog(@"%@",cell.textLabel.text);

    cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow.png" ]];

    return cell;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{  
    CGSize labelSize = CGSizeMake(200.0, 20.0);

    NSString *strTemp = [mutArr objectAtIndex:indexPath.section];

    if ([strTemp length] > 0)
        labelSize = [strTemp sizeWithFont: [UIFont boldSystemFontOfSize: 14.0] constrainedToSize: CGSizeMake(labelSize.width, 1000) lineBreakMode: UILineBreakModeWordWrap];

    return (labelSize.height + 10);
}

Tutaj łańcuch mutArr jest zmienną tablicą, z której pobieram moje dane.

EDIT: - Oto tablica, którą wziąłem.

mutArr= [[NSMutableArray alloc] init];

[mutArr addObject:@"HEMAN"];
[mutArr addObject:@"SUPERMAN"];
[mutArr addObject:@"Is SUPERMAN powerful than HEMAN"];
[mutArr addObject:@"Well, if HEMAN is weaker than SUPERMAN, both are friends and we will never get to know who is more powerful than whom because they will never have a fight among them"];
[mutArr addObject:@"Where are BATMAN and SPIDERMAN"];
 2
Author: Arshad Parwez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-06 13:02:30

Teraz tableviews mogą mieć samorozmiarowe komórki. Ustaw widok tabeli w górę w następujący sposób

tableView.estimatedRowHeight = 85.0 //use an appropriate estimate tableView.rowHeight = UITableViewAutomaticDimension

Apple Reference

 1
Author: Jason,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-12 02:45:11

Stosuję następujące rozwiązania.

Dane są dostarczane oddzielnie w członku:

-(NSString *)getHeaderData:(int)theSection {
    ...
    return rowText;
}

Obsługę można łatwo wykonać w cellForRowAtIndexPath. Zdefiniuj komórkę / zdefiniuj czcionkę i przypisz te wartości do wyniku "komórka". Zauważ, że numberoflines jest ustawione na "0", co oznacza, że weź to, co jest potrzebne.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    UIFont *cellFont = [UIFont fontWithName:@"Verdana" size:12.0];
    cell.textLabel.text= [self getRowData:indexPath.section];
    cell.textLabel.font = cellFont;
    cell.textLabel.numberOfLines=0;
    return cell;
}

W heightForRowAtIndexPath obliczam wysokość zawiniętego tekstu. Rozmiar ciała powinien być związany z szerokością komórki. Dla iPada jest to 1024. Dla iPhone PL iPod 320.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIFont *cellFont = [UIFont fontWithName:@"Verdana" size:12.0];
    CGSize boundingSize = CGSizeMake(1024, CGFLOAT_MAX);
    CGSize requiredSize = [[self getRowData:indexPath.section] sizeWithFont:cellFont constrainedToSize:boundingSize lineBreakMode:UILineBreakModeWordWrap];
    return requiredSize.height;    
}
 0
Author: Vincent,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-06 18:02:31

Uznałem to za dość proste i proste:

[self.tableView setRowHeight:whatEvereight.0f];

Dla np.:

[self.tableView setRowHeight:80.0f];

Może to być najlepsze / standardowe podejście, ale zadziałało w moim przypadku.

 0
Author: Manish Kr. Shukla,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-24 05:46:42

Myślę, że to lepsze i krótsze rozwiązanie. Wystarczy sformatować UILabel (textLabel) komórki, aby automatycznie obliczyć wysokość, określając sizeToFit i wszystko powinno być w porządku.

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell...
    cell.textLabel.text = @"Whatever text you want to put here is ok";
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.numberOfLines = 0;
    [cell.textLabel sizeToFit];

    return cell;
}
 -1
Author: dukz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-06 10:43:34

Nie sądzę, że można manipulować bazą UITableViewCell'sprywatną UILabel, aby to zrobić. Możesz dodać do komórki nową UILabel i użyć numberOfLines z sizeToFit, aby odpowiednio ją powiększyć. Coś w stylu:

UILabel* label = [[UILabel alloc] initWithFrame:cell.frame];
label.numberOfLines = <...an appriate number of lines...>
label.text = <...your text...>
[label sizeToFit];
[cell addSubview:label];
[label release];
 -2
Author: drewh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-06 10:37:53