Swift 自定义委托将不会从ContainerView执行
如果按下了Tableview列表中的一行,我尝试在ViewController中获取事件/操作Swift 自定义委托将不会从ContainerView执行,swift,delegates,Swift,Delegates,如果按下了Tableview列表中的一行,我尝试在ViewController中获取事件/操作 我有以下情节提要: 我的故事板中的Tableview具有故事板ID“myTableViewController” 我的(目标)视图控制器: import UIKit class ViewController: UIViewController, songsDelegate { @IBOutlet weak var label: UILabel! override func viewDi
我有以下情节提要: 我的故事板中的Tableview具有故事板ID“myTableViewController”
我的(目标)视图控制器:
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与委托协议:
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)" )
}
}
我的问题是:为什么
func(\utitle:String)
在ViewController中不执行?您正在实例化TableViewController对象,但没有将其存储到强引用中,也没有将其视图添加为ViewController视图的子视图
let tableviewController = storyboard.instantiateViewController(withIdentifier: "myTableViewController") as! TableViewController
tableviewController.delegate = self
viewDidLoad函数结束时,变量tableviewController将消失请参见: