Come posso creare un UITableViewCell di dimensioni variabili?
-
22-07-2019 - |
Domanda
Non riesco a far sì che il testo si estenda su più righe. Le altezze sembrano corrette. Cosa mi sto perdendo?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"StatusCell"] autorelease];
CGRect frame = cell.contentView.bounds;
UILabel *myLabel = [[UILabel alloc] initWithFrame:frame];
myLabel.text = [[person.updates objectAtIndex:indexPath.row] valueForKey:@"text"];
[cell.contentView addSubview:myLabel];
[myLabel release];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *text = [[person.updates objectAtIndex:indexPath.row] valueForKey:@"text"];
UIFont *font = [UIFont systemFontOfSize:[UIFont systemFontSize]];
CGSize withinSize = CGSizeMake(tableView.frame.size.width, 1000);
CGSize size = [text sizeWithFont:font constrainedToSize:withinSize lineBreakMode:UILineBreakModeWordWrap];
return size.height + 20;
}
Inoltre, cosa mi manca per far apparire le etichette più lunghe della cella della tabella?
Soluzione
Tweetero
fornisce un esempio in MessageListController.m
. Il codice lì visualizza la seguente schermata:
(La foto è tratta da Mashable ).
Schema di implementazione di base:
-
Quando si costruisce un
UITableViewCell
, creare e aggiungere unUILabel
come sottoview nel modo mostrato intableviewCellWithReuseIdentifier:
. Cerca la creazione dell'etichettaTEXT_TAG
. -
quando si arricchisce
UITableViewCell
con le viste, assicurarsi di formattare correttamente l'etichetta, come avviene inconfigureCell: forIndexPath
, allo stesso modo cercare l'etichetta tagTEXT_TAG . -
Restituisce l'altezza appropriata per ogni cella, come avviene in
tableView:heightForRowAtIndexPath
.
Altri suggerimenti
myLabel.numberOfLines = 2;
Controlla docs per informazioni complete su come utilizzare questa proprietà.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return theSizeYouWantYourCellToBe;
}