如何使用 Swift 在表格视图末尾添加提交按钮?

iosiphone/ipadmobile developmentswift更新于 2026/3/2 3:22:17

要在表格视图末尾添加提交按钮,我们可以利用表格视图的页脚。让我们通过一个示例来演示这一点。我们将在表格中添加一个页脚视图,并在表格内部添加用于在表格视图底部添加按钮的代码。

首先创建一个新项目,然后在视图控制器中添加以下代码,该代码将初始化表格,并在表格中添加一个部分和几行。

func initTableView() {
   let tableView = UITableView()
   tableView.frame = self.view.frame
   tableView.dataSource = self
   tableView.delegate = self
   tableView.backgroundColor = colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1)
   tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
   self.view.addSubview(tableView)
}
func numberOfSections(in tableView: UITableView) -> Int {
   return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
   cell?.layer.backgroundColor = colorLiteral(red: 0.2392156869, green:
   0.6745098233, blue: 0.9686274529, alpha: 1)
   cell?.textLabel?.text = "cell at \(indexPath.row)"
   return cell!
}

现在,在视图控制器的 viewDidAppear 方法中调用第一个函数 initTableView()。

现在添加以下代码,该代码将告诉表格为其行和页脚设置一定的高度。

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
   return 60
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
   return 100
}

请确保您已将类确认为 UITableViewDataSource 和 UITableViewDelegate,否则上述方法将显示为错误。

现在,让我们添加一个页脚视图和一个按钮到页脚视图中。

func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
   let footerView = UIView()
   footerView.backgroundColor = colorLiteral(red: 0.9686274529, green:
   0.78039217, blue: 0.3450980484, alpha: 1)
   footerView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height:
   100)
   let button = UIButton()
   button.frame = CGRect(x: 20, y: 10, width: 300, height: 50)
   button.setTitle("自定义按钮", for: .normal)
   button.setTitleColor(colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
   button.backgroundColor = colorLiteral(red: 0.721568644, green:
   0.8862745166, blue: 0.5921568871, alpha: 1)
   footerView.addSubview(button)
   return footerView
}

在设备上运行上述代码后,将生成以下结果。您可以为按钮添加自定义操作,并根据需要进行自定义。



相关文章



关于我们 | 隐私条款 | 学习路线
返回顶部