我正在创建一个 UIView
,其中将包含一个 UITableView
。我想将此 UITableView
委托(delegate)和数据源设置为其父 View 的 View Controller 。
代码:
import UIKit
class AllTasksView: UIView {
let tableview = UITableView()
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func didMoveToSuperview() {
tableview.delegate = "SUPERVIEW.ViewController"
tableview.dataSource = "SUPERVIEW.ViewController"
}
这样可以吗?在哪里最好覆盖
UITableview
方法?我已经在我的 UIViewController
中这样做了。
最佳答案
由于关注点分离,您无法从 UIView
访问 UIViewController
。
或者,您可以使用委托(delegate)来访问 UIViewController
class AllTasksView{
weak var delegate: UITableViewDataSource & UITableviewDelegate?{
didSet{
tableView.delegate = newValue
tableView.dataSource = newValue
}
}
}
额外的
class CustomVC: UIViewController, UITableViewDelegate, UITableViewDataSource{
//implement tableview methods here
func viewDidLoad(){
super.viewDidLoad()
let allTasksView = AllTasksView()
view(addSubview: allTasksView)
//add some positioning and size constraints here for allTasksView
allTasksView.delegate = self //this would call the didSet and would automatically setup the allTasksView.tableView's delegate and dataSource to this vc
}
}
关于ios - 如何从 subview 访问父 View 的 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55863963/