UITableCellView altura variável com subexibição
-
02-07-2019 - |
Pergunta
Eu quero criar um UITableView com diferentes alturas de linha, e eu estou tentando fazer isso criando UILabels dentro das UITableViewCells.
Aqui está o meu código até agora:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = @"EntryCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
}
UILabel *textView = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 300, 40)];
textView.numberOfLines = 0;
textView.text = [entries objectAtIndex:[indexPath row]];
[cell.contentView addSubview:textView];
[textView release];
return cell;
}
Isso me dá 2 linhas de texto por celular. No entanto, cada "entrada" tem um número diferente de linhas, e eu quero que os UITableViewCells para redimensionar automaticamente, quebra de texto conforme necessário, sem alterar o tamanho da fonte.
[textView sizeToFit]
e / ou [cell sizeToFit]
não parecem trabalho.
Aqui está como eu quero o UITableView para olhar:
----------------
Lorem ipsum
----------------
Lorem ipsum
Lorem ipsum
----------------
Lorem ipsum
Lorem ipsum
Lorem ipsum
----------------
Lorem ipsum
----------------
Lorem ipsum
Lorem ipsum
----------------
Alguém sabe como fazer isso corretamente?
Graças.
Solução
O UITableViewDelegate define um heightForRowAtIndexPath método opcional, o que irá ajudar a começar. Você precisa então usar sizeWithFont.
Há alguma discussão sobre o seu problema precisa aqui:
http: // www.v2ex.com/2008/09/18/how-to-make-uitableviewcell-have-variable-height/
dimensionamento de texto também foi discutido em esta discussão
Outras dicas
Esse código funciona para mim. Não sei se ele é perfeito, mas funciona.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.row<[notesModel numberOfNotes]){
NSString *cellText = [@"Your text..."];
UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:12.0];
CGSize constraintSize = CGSizeMake([UIScreen mainScreen].bounds.size.width - 100, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
return labelSize.height + 20;
}
else {
return 20;
}
}
textView.numberOfLines = 2? numberOflines conjuntos nuber máximo de linhas por isso talvez 2 vai owrk para u?