Reputation: 41
I'm creating a UIView
that will have a UITableView
inside it. I want to set this UITableView
delegate and data source equal to the view controller of its superview.
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? I have already done so in my UIViewController
.
Upvotes: 1
Views: 989
Reputation: 873
Due to separation of concerns, you cannot access a UIViewController
from a UIView
.
Alternatively, you can use delegation to access the 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
}
}
Upvotes: 1