Skip to content

6.2_UITableViewDelegate协议方法

UITableViewDelegate 协议提供了许多方法,让你能够自定义 UITableView 的行为和外观。通过实现这些方法,你可以控制单元格的选择、高亮、编辑等,从而创建更丰富、更具交互性的用户体验。准备好深入了解了吗?让我们开始吧!

单元格选择与高亮 ✨

tableView(_:willSelectRowAt:)tableView(_:didSelectRowAt:) 是处理单元格选择的关键方法。前者在单元格即将被选中时调用,允许你阻止选择的发生。后者在单元格被选中后调用,你可以在这里执行诸如导航到新视图控制器或更新数据等操作。

swift
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    // 返回 nil 阻止选择
    return indexPath
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // 处理单元格选择事件
    tableView.deselectRow(at: indexPath, animated: true) // 取消选中状态
    print("你选择了第 \(indexPath.row) 行")
}

自定义单元格外观 🎨

tableView(_:willDisplay:forRowAt:) 方法允许你在单元格显示之前对其进行自定义。你可以修改单元格的背景颜色、字体、添加阴影等。这是一个非常强大的方法,可以让你创建独特且吸引人的列表视图。

swift
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    cell.backgroundColor = indexPath.row % 2 == 0 ? .systemGray6 : .white
    cell.layer.cornerRadius = 10
    cell.clipsToBounds = true
}

单元格高度与估算 📏

tableView(_:heightForRowAt:) 方法用于指定每一行单元格的高度。如果你需要动态调整单元格的高度,可以实现这个方法。tableView(_:estimatedHeightForRowAt:) 方法用于提供一个估计高度,UITableView 可以利用这个估计高度来优化滚动性能。

swift
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 80 // 返回固定的高度
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return 80 // 返回估计的高度
}

编辑与删除 ✂️

UITableViewDelegate 协议还提供了处理单元格编辑和删除的方法。tableView(_:editingStyleForRowAt:) 方法用于指定单元格的编辑风格(插入或删除)。tableView(_:commit:forRowAt:) 方法在用户确认编辑操作后调用,你可以在这里更新数据源。

swift
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
    return .delete // 返回删除风格
}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        // 从数据源中删除数据
        // 更新 UITableView
        print("删除第 \(indexPath.row) 行")
    }
}

头部和尾部视图 📑

你可以使用 tableView(_:viewForHeaderInSection:)tableView(_:viewForFooterInSection:) 方法为每个 section 添加自定义的头部和尾部视图。这些视图可以包含任何你想要显示的内容,例如标题、描述或按钮。

swift
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = UIView()
    headerView.backgroundColor = .lightGray
    return headerView
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 40
}

通过灵活运用 UITableViewDelegate 协议方法,你可以创建出功能强大且用户体验极佳的列表视图。继续探索,你会发现更多惊喜!🎉

本站使用 VitePress 制作