【发布时间】:2020-10-18 10:14:05
【问题描述】:
我只想让我的代码在每个包含文本的表格视图单元格中生成一个按钮。按下按钮时,只需让它打个招呼。每个单元格中都应该有一个按钮。我希望这一切都完成并编写代码,并且根本不使用情节提要。该类应保持为 uiview 控制器且不可更改。
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
private let myArray: NSArray = ["First","Second","Third"]
var myTableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
myTableView.dataSource = self
myTableView.delegate = self
self.view.addSubview(myTableView)
myTableView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
myTableView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.90),
myTableView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1),
myTableView.topAnchor.constraint(equalTo: view.topAnchor),
myTableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
])
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Num: \(indexPath.row)")
print("Value: \(myArray[indexPath.row])")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath as IndexPath)
cell.textLabel!.text = "\(myArray[indexPath.row])"
return cell
}
}
【问题讨论】:
-
创建一个单独的 UITableViewCell 类。在该类中,您可以创建一个函数来在视图控制器加载时配置单元格。然后在代码中创建按钮。然后创建一个不同的函数,为触摸事件设置按钮标题为“hi”。
-
以编程方式搜索“UIButton”?
标签: swift uitableview button cell didselectrowatindexpath