我试图将目标从数组移动到表视图,并且在完成此任务时遇到困难。
这是我的代码。
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的值传递到表视图?
最佳答案
您需要将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
。