swift - 使用按钮将新的 utibableview 单元格添加到索引路径
问题描述
在下面的快速代码中,我想使用按钮箱将另一个 tableview 单元格添加到当前 tableview 中。现在,当代码构建和运行时,代码中有 3 个 tableview 单元格。该按钮应添加 4 单元格,然后在单元格中打印 4 。它应该无限量地这样做。所以 4 5 6 等等。代码不使用故事板。
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "\(indexPath.row)"
return cell
}
var btn = UIButton()
var tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setTableVIew()
btn.backgroundColor = .systemTeal
btn.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(btn)
NSLayoutConstraint.activate([
btn.bottomAnchor.constraint(equalTo: view.bottomAnchor),
btn.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1),
btn.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.2),
])
btn.addTarget(self, action: #selector(pressBtn), for: .touchDown)
}
func setTableVIew(){
let VCframe = self.view.frame
let height = VCframe.height * 0.8
let width = VCframe.width
tableView.frame = CGRect(x: 0, y: 0, width: width, height: height)
tableView.backgroundColor = .clear
tableView.delegate = self
tableView.dataSource = self
self.view.addSubview(tableView)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
@objc func pressBtn(){
//add another cell with the next index so the next number would be 4
}
}
解决方案
简单的方法是numberOfRows
在范围内声明变量ViewController's
并在按下按钮时附加它的值。
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//...
var numberOfRows = 3
//...
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { numberOfRows }
//...
@objc func pressBtn(){
numberOfRows += 1
tableView.reloadData()
}
}
推荐阅读
- python - 为什么我会收到这个奇怪的 Python 错误?OSError:无法打开文件(未找到文件签名)
- rust - 有没有一种安全的方法可以从 Rust 中的可变引用中临时检索拥有的值?
- python - 如何对多维数组进行排序,其中一列按升序排列,另一列按降序排列?
- reactjs - 使用 React 编辑/更新输入字段
- firebase - 如何在flutter中使用Firebase捕获将在通知托盘中显示的消息
- c# - 单一 ID 请求返回 .netcore MVC 中所有 ID 的数组
- algorithm - 有缺陷的棋盘问题是否有蛮力方法?
- javascript - 使用单击删除每个 li 项目待办事项列表
- haskell - Haskell中的异常处理没有解析
- amazon-web-services - 如何在不停机的情况下使用无服务器框架更新 AWS lambda?