我正在尝试使用UIEdgeInsetsMake
将我的单元格背景设置为渐变。我已经尝试了多种方法来使其正常工作,但是不管我用什么,总是有一个问题。
我只是有两个静态单元格,试图将它们的backgroundView
设置为willDisplayCell:
。我有分别用于顶部,底部和中间单元的图像,但是由于我有两个单元,所以我只需要顶部和底部。这些是这些图像:
顶部
底部
底部的顶部缺少一条线,因此它们之间没有2pt的线。我稍微调整了底部的高度以进行补偿(提高了1pt)。这些图像是44x44pt。
我将它们设置如下:
- (void)tableView:(UITableView *)tableView
willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == 0) {
UIImageView *topCellBackgroundImageView =
[[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"grouped-cell-bg-top"]
resizableImageWithCapInsets:UIEdgeInsetsMake(5.0, 5.0, 5.0, 5.0)]];
cell.backgroundView = topCellBackgroundImageView;
}
// If it's the last row
else if (indexPath.row == ([tableView numberOfRowsInSection:0] - 1)) {
UIImageView *bottomCellBackgroundImageView =
[[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"grouped-cell-bg-bottom"]
resizableImageWithCapInsets:UIEdgeInsetsMake(5.0, 5.0, 5.0, 5.0)]];
cell.backgroundView = bottomCellBackgroundImageView;
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
这不能很好地工作。如下图所示,在顶部单元格中,单元格上有一个1pt的白色“带”,看起来很丑陋。我不知道为什么会在那里。
因此,我将
topCellBackgroundView
更改为具有(5.0, 5.0, 0.0, 5.0)
的边缘插图,因为由于它仅在顶部四舍五入,因此不需要考虑bottom
属性(它是平坦的)。很好用!除非您选择该单元格,否则底部单元格将不再占用其整个单元格。我应该做些什么?看来不管我做什么,都行不通。我也尝试了1.0而不是0.0,以及-1.0无济于事。
最佳答案
好消息:您不会发疯。您的可拉伸(stretch)图像代码可能很完美。问题是,具有分组样式的UITableView除了为heightForRowAtIndexPath:
返回的值之外,还为单元格的高度添加了额外的点
因此,解决问题的方法是根据该部分中的总行数,在heightForRowAtIndexPath:
中返回调整后的单元格高度:
- (CGFloat)heightForRow:(NSIndexPath *)indexPath {
CGFloat standardHeight = 44.0f;
NSInteger numberOfRowsInSection = [self numberOfRowsInSection:indexPath.section];
if (numberOfRowsInSection == 1) {
standardHeight -= 2;
}
else if (indexPath.row == 0 || indexPath.row == numberOfRowsInSection-1) {
standardHeight -= 1;
}
return standardHeight;
}
这是显示UITableView如何执行此操作的示例图像:
据我所知,只有分组的样式表 View 会受到影响,即使这样,效果也会根据给定节中的总行数发生变化:
据我所知,这是如此令人沮丧,并且从未被记录下来。 :-)
更新
上面的计算是针对使用默认分隔符样式
UITableViewCellSeparatorStyleSingleLineEtched
的分组样式表 View 的。在其他情况下(即UITableViewCellSeparatorStyleSingleLine
和UITableViewCellSeparatorStyleNone
),这是要执行的操作:- (CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CGFloat rowHeight = 44.0f;
if (indexPath.row == 0) {
rowHeight -=1;
}
return rowHeight;
}
关于ios - UIEdgeInsets在单元格上创建一个奇怪的带,我不知道如何解决它,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17513989/