ios - 试图将数组移动到表格视图
问题描述
我正在尝试将目标从数组移动到 tableview 并且无法完成此任务。
这是我的代码。
import UIKit
class GoalsViewController: UIViewController {
@IBOutlet weak var goalTableView: UITableView!
@IBOutlet weak var goalCategoryLabel: UILabel!
var valueToPass = ""
var goals: [String] = []
let theEmptyModel: [String] = ["No data in this section."]
var firstGoals = ["run", "walk", "jog"]
var secondGoals = ["sleep", "rest"]
var goalCategoryText: String = ""
override func viewDidLoad() {
super.viewDidLoad()
goals = firstGoals
goalCategoryLabel?.text = goalCategoryText
goalTableView.delegate = self
goalTableView.dataSource = self
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "firstGoalsSegue" {
if goalCategoryText == "First Goals" {
let viewController = segue.destination as! GoalsViewController
viewController.firstGoals.append(valueToPass)
}
}
if segue.identifier == "secondGoalsSegue" {
if goalCategoryText == "Second Goals" {
let viewController = segue.destination as! GoalsViewController
viewController.secondGoals.append(valueToPass)
}
}
}
extension GoalsViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return goals.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "GoalsCell_1", for: indexPath)
cell.textLabel?.text = goals[indexPath.row]
cell.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
cell.textLabel?.numberOfLines = 3
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "\(sectionHeader)"
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
valueToPass = goals[indexPath.row]
performSegue(withIdentifier: "firstGoalsSegue", sender: self)
performSegue(withIdentifier: "secondGoalsSegue", sender: self)
tableview.reloadData()
}
}
当前,选择一个按钮时,我被带到只显示空单元格的桌面屏幕。我将如何修复我的代码,以便在点击受尊重的按钮时将 firstGoals 和 secondGoals 的值传递给 tableview?
解决方案
您需要将GoalTableView
'delegate
和dataSource
设置为GoalsViewController
,如下所示:
override func viewDidLoad() {
super.viewDidLoad()
goals = ["goal 1", "goal 2", "goal 3"]
goalCategoryLabel?.text = goalCategoryText
GoalTableView.delegate = self
GoalTableView.dataSource = self
GoalTableView.reloadData()
}
提示:尝试为实例保留以小写字母开头的名称,在这种情况下重命名GoalTableView
为goalTableView
.
推荐阅读
- php - PHP:独立于平台的shebang放在PHP文件的顶部以随处使用PHP CLI执行它们?
- c++ - 将 HEX 转换为 DEC
- google-account - 为域创建 Google 帐户时出现问题
- android - 显示状态栏android
- java - 如何通过 Class.forName(...) 获取数组的类?
- javascript - 从服务订阅数据时,类型 void 上不存在错误属性订阅?
- javascript - Angular *ngFor在循环抛出对象时使用PIPE不起作用
- flutter - Flutter & Background fetch - 如何处理一个简单的例子?
- html - 在 nextjs 中将背景图像设置为 div 不起作用
- python-3.x - 熊猫:MID & FIND 功能