美文网首页
iOS 代码实现select tableView row

iOS 代码实现select tableView row

作者: Sakumi | 来源:发表于2022-06-20 16:44 被阅读0次

    项目背景

    在项目中经常会有这样的需求:打开列表要勾选用户当前选中的一项。这时,就需要用代码来选择tableView的row了。

    以下两种方式都可以到达此效果:

    方法一:

    selectRowAtIndexPath
    首先在代码中实现selectRowAtIndexPath方法,接着在tableView的delegate中实现tableView:willDisplayCell
    需要注意的是:selectRowAtIndexPath并不会走到tableView:willSelectRowAtIndexPathtableView:didSelectRowAtIndexPathUITableViewSelectionDidChangeNotification代理方法中,所以要在tableView:willDisplayCell中实现选中效果

    实例代码:

    // 选中第x项
    tableView.selectRow(at: IndexPath(row: x, section: 0), animated: false, scrollPosition: .none)
    // 在delegate中修改选中项的样式
    extension DemoViewController: UITableViewDelegate, UITableViewDataSource {
        func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
            if cell.isSelected {
                // 实现选中效果
            }
        }
    }
    

    但有些场景下,tableView已经绘制完成,方法一就不适用了,就需要用到

    方法二:

    直接调用tableView(tableView, didSelectRowAt: indexPath)

    实例代码:

    // 选中第x项
    tableView(tableView, didSelectRowAt: IndexPath(row: x, section: 0))
    // 在delegate中修改选中项的样式
    extension DemoViewController: UITableViewDelegate, UITableViewDataSource {
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            for _ in 0...tableViewData.count - 1 {
                if (tableView.cellForRow(at: indexPath) as! DemoTableViewCell).isSelected {
                    // 取消之前的选中样式
                }
            }
            // 实现选中效果
        }
    }
    

    OC语言实现方式可以参考:

    https://stackoverflow.com/questions/2035061/select-tableview-row-programmatically

    写在最后

    友友们,我转iOS开发啦,以后不更新Android了。我和我对象会用这个账号一起分享iOS开发相关内容,大家一起努力哦~

    相关文章

      网友评论

          本文标题:iOS 代码实现select tableView row

          本文链接:https://www.haomeiwen.com/subject/eajjvrtx.html