UITable View Cellの背景
37189 ワード
http://haoxiang.org/2010/12/uitableviewcell-background/
UITable View Cellはよく使われているViewです.私たちはいつも直接にそれを使います.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier] autorelease];
}
cell.textLabel.text = [NSString stringWithFormat:@"Line: %d", indexPath.row];
return cell;
}
この効果を得る:今はテーブルビューセルに背景色を追加します.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier] autorelease];
}
cell.textLabel.text = [NSString stringWithFormat:@"Line: %d", indexPath.row];
// cell.backgroundColor = [UIColor blueColor];
cell.contentView.backgroundColor = [UIColor blueColor];
return cell;
}
私たちは直接にセル.background Colorを使うべきではない.Cell自体はUID Viewです.私たちが見ている部分は実はSubviewだけです.つまり、cell.co ntViewです.ですから、セル自体の背景色を直接変えても、セル.でも、cell.co ntView.background Colorで背景色を変えるのは一番いいPracticeではないです.
tableView.editing = YES;
エディットモードに入ると問題が発生します.Cocoaが提供するボタンの背景色は透明です.ContintViewが移されたので、下はテーブルビューの色です.もうセルの一部ではありません.
そのため、最も良い方法は、cell.background Viewによってcellの背景を変えるべきです.文書の説明によると、background Viewは常にセルの一番下の階にありますので、セルの中の他のsubviewの背景を「UIClor clearColor」として、cell.background Viewを統一の背景として、一番いい方法です.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier] autorelease];
}
cell.textLabel.text = [NSString stringWithFormat:@"Line: %d", indexPath.row];
cell.textLabel.backgroundColor = [UIColor clearColor];
UIView *backgrdView = [[UIView alloc] initWithFrame:cell.frame];
backgrdView.backgroundColor = [UIColor blueColor];
cell.backgroundView = backgrdView;
[backgrdView release];
return cell;
}
効果: