【发布时间】:2020-04-01 12:11:35
【问题描述】:
我想要多个单元格,每个单元格中都有一个标签。 但作为最后一个单元格,我想要一个按钮而不是标签,它应该导航回我的主视图控制器。
标签正在工作,但我无法制作一个带有按钮的单元格运行。这是我的 UITableViewController 代码:
class StatsViewController: UITableViewController {
var vc = ViewController()
override func viewDidLoad() {
super.viewDidLoad()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let cell2 = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath)
if let label = cell.viewWithTag(1000)as? UILabel{
if indexPath.row == 0 {
label.text = "Row 0"
}
else if indexPath.row == 1{
label.text = "Row 1"
}
else if indexPath.row == 2{
label.text = "Row 2"
}
else if indexPath.row == 3{
label.text = "Row 3"
}
return cell
}
if let button = cell2.viewWithTag(1001) as? UIButton {
if indexPath.row == 4{
return cell2
}
}
return UITableViewCell()
}
}
我将情节提要中的标签单元格标识为“cell”,将按钮单元格标识为“cell2”。
然后我用值“1000”标记标签,并且单元格2中的按钮有 Tag = 1001
(WEITER 是按钮)
感谢@Sh_Khan 和@ 这样的方式编辑了我的代码。现在,它确实向我显示了按钮,但没有显示标签..
class StatsViewController: UITableViewController {
var vc = ViewController()
override func viewDidLoad() {
super.viewDidLoad()
// tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
// tableView.reloadData()
//tableView.delegate = self
}
let timestamp = DateFormatter.localizedString(from: NSDate() as Date, dateStyle: .medium, timeStyle: .short)
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellId = (indexPath.row == 4) ? "cell2" : "cell"
if let label = cell.viewWithTag(1000)as? UILabel{
if indexPath.row == 0 {
label.text = "Row 0"
}
else if indexPath.row == 1{
label.text = "Row 1"
}
else if indexPath.row == 2{
label.text = "Row 2"
}
else if indexPath.row == 3{
label.text = "Row 3"
}
return tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
}
if let button = cell2.viewWithTag(1001) as? UIButton {
if indexPath.row == 4{
return tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
}
}
return UITableViewCell()
}
}
【问题讨论】:
-
您可以将按钮单元格用作 tableView 的页脚视图。
标签: ios swift xcode uitableview