我正在尝试将背景大小设置为比默认值短一点,从而在单元格之间创建一些空间。事实证明这很困难。设置背景 View 的框架似乎没有任何作用:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *reuseIdentifier = @"cell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
if (!cell)
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
// Set up the cell...
cell.contentView.backgroundColor = [UIColor clearColor];
cell.backgroundView = [[[UIView alloc] initWithFrame:CGRectMake(0, 4, 320, 42)] autorelease];
cell.backgroundView.backgroundColor = [UIColor blackColor];
cell.backgroundView.alpha = .2;
cell.selectedBackgroundView = [[[UIView alloc] initWithFrame:CGRectMake(0, 4, 320, 42)] autorelease];
cell.selectedBackgroundView.backgroundColor = [UIColor whiteColor];
cell.selectedBackgroundView.alpha = .2;
cell.font = [UIFont fontWithName:@"MarkerFelt-Thin" size:22.0f];
cell.selectedTextColor = [UIColor blackColor];
cell.textColor = [UIColor whiteColor];
NSDictionary *dict = [files objectAtIndex:indexPath.row];
cell.text = [dict objectForKey:@"name"];
return cell;
}
有什么帮助吗?
此外,设置选定的背景 View 不会执行任何操作。选择单元格后,背景完全空白。这是为什么?
我使用的是 iPhone OS 2.2.1。
我也这样做:
- (void)viewDidLoad
{
[super viewDidLoad];
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
self.tableView.backgroundColor = [UIColor clearColor];
self.tableView.rowHeight = 50.0f;
}
您可以在此处下载代码(仅针对此问题制作了一个小项目):
最佳答案
backgroundView 不是一个普通的 View ,幕后发生了一些事情。查看此链接:
Difference between background view and content view in uitableviewcell
具体来说,来自文档:
背景 View : 对于普通样式表 (UITableViewStylePlain) 中的单元格,默认值为 nil;对于分组样式表 (UITableViewStyleGrouped) 中的单元格,默认值为非 nil。 UITableViewCell 将背景 View 添加为所有其他 View 后面的 subview ,并使用其当前帧位置。
因此:它实际上没有框架位置,它使用单元格的框架位置。
此代码有效:
UIImageView *bgView = [[UIImageView alloc] init]; // Creating a view for the background...this seems to be required.
bgView.backgroundColor = [UIColor redColor];
cell.backgroundView = bgView;
UIImageView *bgImageView = [[UIImageView alloc] init]; // Creating a subview for the background...
bgImageView.backgroundColor = [UIColor colorWithWhite:1 alpha:1];
[bgImageView setFrame:CGRectInset(cell.bounds, 1, 1)];
[cell.backgroundView addSubview:bgImageView]; // Assigning the subview, and cleanup.
[bgImageView release];
[bgView release];
花了大约一个小时试图解决这个问题......但它有效。这是 cellForRowAtIndexPath 委托(delegate)方法中的代码——显然我不会在这里介绍全部内容。
关于iphone - UITableViewCell背景大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2320204/