iPhone + UITableView +セルのフォーマット
-
05-07-2019 - |
質問
アプリケーションで次のメソッドを使用しています:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.row == 0)
{
cell.contentView.backgroundColor = [UIColor lightGrayColor];
cell.contentView.alpha = 0.5;
}
}
アプリケーションを実行すると、テーブルに7行あります。上記の関数によると、最初の行(行番号0)のセルのみをフォーマットする必要があります(if条件のため)。
1行目のセル(行番号0)は適切にフォーマットされています(目的の出力に従って)。ただし、テーブルを下にスクロールすると、もう1つのセルがフォーマット済みとして表示されます:行番号5のセル
なぜですか?
解決
ウラジミールの答えに同意します。 ただし、別のアプローチに従う必要もあります。
現在の状況では、各スクロールでメソッドが呼び出されるため、セルを頻繁にフォーマットしているため、パフォーマンスが最適化されていません。
よりエレガントなソリューションは、1行目を他の「1回限り」とは異なる方法でフォーマットすることです。 :セルを作成するとき。
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier;
if(indexPath.row == 0)
CellIdentifier = @"1stRow";
else
CellIdentifier = @"OtherRows";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
if(indexPath.row == 0){
cell.contentView.backgroundColor = [UIColor lightGrayColor];
cell.contentView.alpha = 0.5;
// Other cell properties:textColor,font,...
}
else{
cell.contentView.backgroundColor = [UIColor blackColor];
cell.contentView.alpha = 1;
//Other cell properties: textColor,font...
}
}
cell.textLabel.text = .....
return cell;
}
他のヒント
その理由は、TableViewが既存のセルを再利用し、可能であればそれらを表示するからだと思います。ここで何が起こるか-テーブルがスクロールされ、行0が非表示になると、対応するセルが新しく表示された行に使用されます。したがって、セルを再利用する場合は、プロパティをリセットする必要があります。
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.row == 0) {
cell.contentView.backgroundColor = [UIColor lightGrayColor];
cell.contentView.alpha = 0.5; }
else
{
// reset cell background to default value
}
}
所属していません StackOverflow