如何知道UITableView行号

如何知道UITableView行号

我有一个UITableViewCell带着UISwitch作为每个单元格的辅助视图。当我在单元格中更改开关的值时,如何知道开关在哪一行?我需要切换值更改事件中的行号。



小怪兽爱吃肉
浏览 435回答 3
3回答

ibeautiful

如果您设置tag属性设置为行号(如其他答案所建议的),您必须在tableView:cellForRowAtIndexPath:(因为可以对不同的行重用单元格)。相反,当您需要行号时,您可以沿着superview链子UISwitch(或任何其他视图)UITableViewCell,然后到UITableView,并询问单元格的索引路径的表视图:static NSIndexPath *indexPathForView(UIView *view) {     while (view && ![view isKindOfClass:[UITableViewCell class]])         view = view.superview;     if (!view)         return nil;     UITableViewCell *cell = (UITableViewCell *)view;     while (view && ![view isKindOfClass:[UITableView class]])         view = view.superview;     if (!view)         return nil;     UITableView *tableView = (UITableView *)view;     return [tableView indexPathForCell:cell];}这不需要在tableView:cellForRowAtIndexPath:.

慕雪6442864

接受的解决方案是一种聪明的攻击。但是,如果我们可以利用已经可用的,为什么我们需要使用hitpoint呢?tag财产上UIView?你会说标记只能存储行或节。因为它是单曲INT.好吧.。别忘了你的根人(CS 101)。单曲INT可以存储两个两倍小的整数。这里有一个扩展:extension&nbsp;Int&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;init(indexPath:&nbsp;IndexPath)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;marshalledInt:&nbsp;UInt32&nbsp;=&nbsp;0xffffffff &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;rowPiece&nbsp;=&nbsp;UInt16(indexPath.row) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;sectionPiece&nbsp;=&nbsp;UInt16(indexPath.section) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;marshalledInt&nbsp;=&nbsp;marshalledInt&nbsp;&&nbsp;(UInt32(rowPiece)&nbsp;<<&nbsp;16) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;marshalledInt&nbsp;=&nbsp;marshalledInt&nbsp;+&nbsp;UInt32(sectionPiece) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;self.init(bitPattern:&nbsp;UInt(marshalledInt)) &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;indexPathRepresentation:&nbsp;IndexPath&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;section&nbsp;=&nbsp;self&nbsp;&&nbsp;0x0000ffff &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;pattern:&nbsp;UInt32&nbsp;=&nbsp;0xffff0000 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;row&nbsp;=&nbsp;(UInt32(self)&nbsp;&&nbsp;pattern)&nbsp;>>&nbsp;16 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;IndexPath(row:&nbsp;Int(row),&nbsp;section:&nbsp;Int(section)) &nbsp;&nbsp;&nbsp;&nbsp;}}在你的tableView(_:, cellForRowAt:)然后你可以:cell.yourSwitch.tag&nbsp;=&nbsp;Int(indexPath:&nbsp;indexPath)然后在操作处理程序中可以:func&nbsp;didToogle(sender:&nbsp;UISwitch){ &nbsp;&nbsp;&nbsp;&nbsp;print(sender.tag.indexPathRepresentation)}不过,请注意它的局限性:行和区段不需要大于65535。(UInt 16.max)我怀疑你的tableView的指数会那么高,但如果它们是这样的话,挑战你自己,并实施更有效的包装方案。假设我们有一个很小的部分,我们不需要所有的16位来表示一个节。我们的int布局如下:{section&nbsp;area&nbsp;length}{all&nbsp;remaining}[4&nbsp;BITS:&nbsp;section&nbsp;area&nbsp;length&nbsp;-&nbsp;1]那是我们的4LSBs指定区段区域-1的长度,因为我们至少为一个区段分配了1位。因此,在我们的部分为0的情况下,行最多可以占用27位([1][27][4]),这绝对是足够的。
打开App,查看更多内容
随时随地看视频慕课网APP