Pobierz niestandardową wysokość komórki prototypu z serii ujęć?
Podczas używania „Dynamicznych prototypów” do określaniaUITableView
zawartość w serii ujęć, istnieje właściwość „Wysokość wiersza”, którą można ustawić na Niestandardową.
Podczas tworzenia instancji komórek ta niestandardowa wysokość wiersza nie jest brana pod uwagę. Ma to sens, ponieważ o używanej komórce prototypowej decyduje mój kod aplikacji w momencie, gdy komórka ma zostać utworzona. Aby utworzyć instancję wszystkich komórek podczas obliczania układu, wprowadzono by obniżenie wydajności, więc rozumiem, dlaczego nie można tego zrobić.
Pytanie może więc w jakiś sposób odzyskać wysokość podaną w identyfikatorze ponownego użycia komórki, np.
[myTableView heightForCellWithReuseIdentifier:@"MyCellPrototype"];
czy coś takiego? Czy muszę zduplikować wyraźne wysokości wierszy w moim kodzie aplikacji, z następującymi obciążeniami związanymi z konserwacją?
Rozwiązany za pomocą @TimothyMoose:
Wysokości są przechowywane w samych komórkach, co oznacza, że jedynym sposobem uzyskania wysokości jest utworzenie instancji prototypów. Jednym ze sposobów na to jest wstępne usunięcie kolejki z komórek poza normalną metodą wywołania zwrotnego komórki. Oto mój mały POC, który działa:
#import "ViewController.h"
@interface ViewController () {
NSDictionary* heights;
}
@end
@implementation ViewController
- (NSString*) _reusableIdentifierForIndexPath:(NSIndexPath *)indexPath
{
return [NSString stringWithFormat:@"C%d", indexPath.row];
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(!heights) {
NSMutableDictionary* hts = [NSMutableDictionary dictionary];
for(NSString* reusableIdentifier in [NSArray arrayWithObjects:@"C0", @"C1", @"C2", nil]) {
CGFloat height = [[tableView dequeueReusableCellWithIdentifier:reusableIdentifier] bounds].size.height;
hts[reusableIdentifier] = [NSNumber numberWithFloat:height];
}
heights = [hts copy];
}
NSString* prototype = [self _reusableIdentifierForIndexPath:indexPath];
return [heights[prototype] floatValue];
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 3;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString* prototype = [self _reusableIdentifierForIndexPath:indexPath];
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:prototype];
return cell;
}
@end