为了账号安全,请及时绑定邮箱和手机立即绑定

如何知道UITableView行号

如何知道UITableView行号

小怪兽爱吃肉 2019-07-05 13:39:57
如何知道UITableView行号我有一个UITableViewCell带着UISwitch作为每个单元格的辅助视图。当我在单元格中更改开关的值时,如何知道开关在哪一行?我需要切换值更改事件中的行号。
查看完整描述

3 回答

?
ibeautiful

TA贡献1993条经验 获得超5个赞

如果您设置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:.


查看完整回答
反对 回复 2019-07-05
?
慕雪6442864

TA贡献1812条经验 获得超5个赞

接受的解决方案是一种聪明的攻击。

但是,如果我们可以利用已经可用的,为什么我们需要使用hitpoint呢?tag财产上UIView?你会说标记只能存储行或节。因为它是单曲INT.

好吧.。别忘了你的根人(CS 101)。单曲INT可以存储两个两倍小的整数。这里有一个扩展:

extension Int {

    public init(indexPath: IndexPath) {
        var marshalledInt: UInt32 = 0xffffffff

        let rowPiece = UInt16(indexPath.row)
        let sectionPiece = UInt16(indexPath.section)
        marshalledInt = marshalledInt & (UInt32(rowPiece) << 16)
        marshalledInt = marshalledInt + UInt32(sectionPiece)

        self.init(bitPattern: UInt(marshalledInt))
    }

    var indexPathRepresentation: IndexPath {
        let section = self & 0x0000ffff

        let pattern: UInt32 = 0xffff0000
        let row = (UInt32(self) & pattern) >> 16
        return IndexPath(row: Int(row), section: Int(section))
    }}

在你的tableView(_:, cellForRowAt:)然后你可以:

cell.yourSwitch.tag = Int(indexPath: indexPath)

然后在操作处理程序中可以:

func didToogle(sender: UISwitch){
    print(sender.tag.indexPathRepresentation)}

不过,请注意它的局限性:行和区段不需要大于65535。(UInt 16.max)

我怀疑你的tableView的指数会那么高,但如果它们是这样的话,挑战你自己,并实施更有效的包装方案。假设我们有一个很小的部分,我们不需要所有的16位来表示一个节。我们的int布局如下:

{section area length}{all remaining}[4 BITS: section area length - 1]

那是我们的4LSBs指定区段区域-1的长度,因为我们至少为一个区段分配了1位。因此,在我们的部分为0的情况下,行最多可以占用27位([1][27][4]),这绝对是足够的。


查看完整回答
反对 回复 2019-07-05
  • 3 回答
  • 0 关注
  • 424 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信