【发布时间】:2018-09-04 21:04:03
【问题描述】:
我尝试在我的 ViewController 中获取一个事件/动作,如果我的 Tableview 中的一行被按下。
我有以下故事板:
我的 Storyboard 中的 Tableview 的 StoryboardID 为“myTableViewController”
我的(目的地)ViewController:
import UIKit
class ViewController: UIViewController, songsDelegate {
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = UIColor.red
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let tableviewController = storyboard.instantiateViewController(withIdentifier: "myTableViewController") as! TableViewController
tableviewController.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func songTapped(_ title: String) {
print(" action ")
self.label.text = title
}
}
我的(响应)TableViewController 使用 Delegate 协议:
import UIKit
protocol songsDelegate: class {
func songTapped(_ title: String)
}
class TableViewController: UITableViewController {
weak var delegate : songsDelegate?
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 12
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = "Titel \(indexPath.row + 1)"
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(indexPath.row)
self.delegate?.songTapped( "Titel \(indexPath.row + 1)" )
}
}
我的问题是:为什么ViewController中的func songTapped(_ title: String)不会被执行?
【问题讨论】: