ios - 使用部分页脚 View 向页脚 View 所在的部分添加一行?

标签 ios swift uitableview

我想知道是否可以创建一个 UITableView,当用户点击一个部分页脚 View (包含一个 UIButton,比方说)时,添加一行到点击部分页脚 View 所在的部分。

在尝试创建这样一个 UITableView 时,我意识到存在一个重大挑战,即我无法获得对点击部分页脚 View 所在部分的引用。因此,我不能使用像 insertRows(at:with:) 这样的方法来完成所需的添加。

有什么方法可以获取行的引用吗?或者有什么方法可以让 UITableView 在点击部分页脚 View 时“知道”在何处插入行?

最佳答案

有几种方法可以做到这一点,但最简单的可能是在页脚 View 中添加一个手势识别器——您不需要按钮,您可以在任何地方检查是否有点击,但您的设计可能会更好带有一个按钮,具体取决于您在页脚 View 中包含的内容。

您可以使用tag 属性来跟踪该部分,并且处理起来很容易。

这是一个简单的例子,我假设 data1data2 出现在两个部分中

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "tableViewCell", for: indexPath) as UITableViewCell

    if indexPath.section == 0
    {
        cell.textLabel?.text = data1[indexPath.row]
    }
    else
    {
        cell.textLabel?.text = data2[indexPath.row]
    }
    return cell
}

func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let footerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 30))
    footerView.backgroundColor = UIColor.blue
    footerView.tag = section

    let clickGesture = UITapGestureRecognizer(target: self, action:  #selector(self.didClickFooter))
    footerView.addGestureRecognizer(clickGesture)


    return footerView
}
@objc func didClickFooter(sender : UITapGestureRecognizer) {
    // Do what you want here, once you identify the section

    if sender.view!.tag == 0
    {
        data1.append("new data1")
    }
    else
    {
        data2.append("new data2")
    }
    tableView.reloadData()

}

关于ios - 使用部分页脚 View 向页脚 View 所在的部分添加一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55898861/

相关文章:

ios - jQuery Ui Sortable 的延迟选项在 iOS 上不起作用

swift - 为什么我们在 Swift 变量声明中使用关键字 "get"?

ios - 请求相机权限时 requestAccessForMediaType 的响应崩溃

iphone - 合并 UITableViewCells

swift - tableview 不显示 firebase 用户

ios - Ionic 3 - 无法在 iOS 上安装生产应用程序

ios - 如何在xcode7中找到libicucore.dylib?

iphone - UITableView 背景作为平铺图像

ios - UIView 上的渐变蒙版

swift - tableView 在应该刷新后不刷新(由单独的类调用) - swift