快速的UITableView动态数据源/代理 [英] Dynamic datasource/delegates for UITableView in swift
问题描述
我需要根据特定条件设置不同的对象作为数据源&表视图的委托.
I need to set up different objects based on certain conditions as the datasource & delegate for table view.
但是我无法分配tableview的数据源/委托,因为它会引发一些错误.
But I am not able to assign tableview's datasource/delegate as it throws some errors.
无法分配NSObject类型的值?到UITableViewDelegate类型的值?
Cannot assign a value of type NSObject? to a value of type UITableViewDelegate?
我确实检查了此问题与解答,但没用.
I did check this Q&A but this did not work.
var dataSourceDelegate:NSObject?
class RootViewController: UIViewController {
...
override func viewDidLoad() {
dataSourceDelegate = TableDataSourceDelegate()
// Table View
tableView = UITableView()
tableView!.setTranslatesAutoresizingMaskIntoConstraints(false)
tableView!.dataSource = dataSourceDelegate
// Cannot assign a value of type NSObject? to a value of type UITableViewDataSource?
tableView!.delegate = dataSourceDelegate
// Cannot assign a value of type NSObject? to a value of type UITableViewDelegate?
view.addSubview(tableView!)
// Constraints
var views:[String:UIView] = ["table":tableView!]
var hTableConstraint = "H:|[table]|"
var vConstraint = "V:|[table]|"
view.addConstraintsToView([hTableConstraint, vConstraint], view: view, viewVariables: views)
}
...
}
这是数据源/委托类
class TableDataSourceDelegate:NSObject, UITableViewDataSource, UITableViewDelegate {
// MARK: Datasource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return UITableViewCell()
}
// MARK: Delegates
}
推荐答案
NSObject?不符合UITableViewDelegate,也不符合UITableViewDataSource.您应该像这样创建协议
NSObject? doesn't conforms to UITableViewDelegate, neither to UITableViewDataSource. You should create your protocol like
protocol GeneralDataSource: UITableViewDataSource, UITableViewDelegate {}
然后所有数据源都应遵循该协议.
And then all data sources should conform that protocol.
class MyDataSource: NSObject, GeneralDataSource {
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return UITableViewCell()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
}
然后您可以像这样使用它
Then you can use it like this
var myDataSource: GeneralDataSource?
override func viewDidLoad() {
super.viewDidLoad()
self.myDataSource = MyDataSource()
self.tableView.delegate = self.myDataSource
}
这篇关于快速的UITableView动态数据源/代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!