[英]How to access a superview's view controller from a child view
I'm creating a UIView
that will have a UITableView
inside it.我正在创建一个
UIView
,里面有一个UITableView
。 I want to set this UITableView
delegate and data source equal to the view controller of its superview.我想将此
UITableView
委托和数据源设置为其超级视图的视图控制器。
Code:代码:
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"
}
Is it possible to do so like this?可以这样做吗? and where is it best to
override
the UITableview
methods?在哪里最好
override
UITableview
方法? I have already done so in my UIViewController
.我已经在我的
UIViewController
这样做了。
Due to separation of concerns, you cannot access a UIViewController
from a UIView
.由于关注点分离,您无法从
UIView
访问UIViewController
。
Alternatively, you can use delegation to access the UIViewController
或者,您可以使用委托来访问
UIViewController
class AllTasksView{
weak var delegate: UITableViewDataSource & UITableviewDelegate?{
didSet{
tableView.delegate = newValue
tableView.dataSource = newValue
}
}
}
ADDITIONAL额外的
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.