我正在尝试从viewController中分离dataSource和delegate,以防止viewController变得混乱.我阅读了一些帖子,发现我可以像下面一样分开dataSource,创建一个类来表示dataSource:
import UIKit
class DataSource: NSObject, UITableViewDataSource, UITableViewDelegate {
var movies = [String]()
//MARK: - UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return movies.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cellIdentifier", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = movies[indexPath.row]
return cell
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:如果我想viewController在DataSource类中使用属性或调用类的方法,我该怎么办?例如,我想presentViewController在用户选择单元格时调用:
func tableView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//do something here
presentViewController(viewController!, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)
您可以处理选定的回调:
class DataSource: NSObject, UITableViewDataSource, UITableViewDelegate {
var movies = [String]()
private var selectedCallback = ((NSIndexPath)->Void)?
func selectedItemAtIndex(callback:(NSIndexPath) -> Void) {
selectedCallback = callback
}
}
Run Code Online (Sandbox Code Playgroud)
打回来:
func tableView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//do something here
if let callback = selectedCallback {
callback(indexPath)
}
}
Run Code Online (Sandbox Code Playgroud)
使用:
dataSource.selectedItemAtIndex() {
[weak self] indexPath in
// do something ...
// presentViewController(viewController!, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2401 次 |
| 最近记录: |