UITableViewCell如何知道自己的indexPath?

Ed *_*rty 26 iphone uitableview

标准的分组UITableView样式允许UITableViewCell在每个部分的顶部和底部绘制带圆角的s.这是如何完成的?细胞如何在其部分内知道自己的位置,以及它如何知道何时更改其圆形边缘?

我想制作自己的圆形单元格,并且我有要使用的图像,但不知道何时显示哪个图像

注意:我已经知道UITableView是如何工作的,我知道如何使用它.我只是认为,因为UITableView能够在正确的位置自动绘制圆角,所以我也应该能够,无需向我的数据源或委托添加任何内容.

小智 61

NSIndexPath *indexPath = [(UITableView *)self.superview indexPathForCell: self];
int rows = [(UITableView *)self.superview numberOfRowsInSection:indexPath.section];

if (indexPath.row == 0 && rows == 1) {
// the one and only cell in the section
}
else if (indexPath.row == 0) {
//top
}
else if (indexPath.row != rows - 1) {
//middle
}
else {
//bottom
}
Run Code Online (Sandbox Code Playgroud)

  • 此解决方案将来可能不再有效.你不能预测你的UITableViewCell是它的tableview的直接子视图...... (2认同)

小智 32

这很简单.假设单元格是对象,其位置将被发现.

  UITableView* table = (UITableView *)[cell superview]; 
  NSIndexPath* pathOfTheCell = [table indexPathForCell:cell]; 
  NSInteger sectionOfTheCell = [pathOfTheCell section]; 
  NSInteger rowOfTheCell = [pathOfTheCell row];
Run Code Online (Sandbox Code Playgroud)


ale*_*leh 8

sectionLocation方法UITableViewCell返回整数告诉你你需要什么:

  • 1 - 中间细胞
  • 2 - 顶部细胞
  • 3 - 底部细胞
  • 4 - 单细胞

自2010年以来,我在几个生产应用中使用它没有任何问题.

更新:我们的一个二进制文件最近被自动拒绝(2018年底),因为我们使用的是"sectionLocation"属性,所以它不再是一个好的选择.

将这样的内容添加到头文件中,您可以使用它:

typedef NS_ENUM(NSInteger, MMMTableViewCellLocation) {

    MMMTableViewCellLocationUndefined = 0,
    MMMTableViewCellLocationMiddle = 1,
    MMMTableViewCellLocationTop = 2,
    MMMTableViewCellLocationBottom = 3,
    MMMTableViewCellLocationSingle = 4
};

@interface UITableViewCell ()

/** Undocumented method of UITableViewCell which allows to know where within section the cell is located,
 * so the cell can draw its borders properly. */
- (MMMTableViewCellLocation)sectionLocation;

/** Override this one to know when the value of sectionLocation changes. */
- (void)setSectionLocation:(MMMTableViewCellLocation)sectionLocation animated:(BOOL)animated;

@end
Run Code Online (Sandbox Code Playgroud)