内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
我试图保持视图控制器的清洁,根据objc.io Issue #1 Lighter View Controllers。我在目标C中测试了这个方法,而且效果很好。我有一个单独的类,它实现UITableViewDataSource
方法。
#import "TableDataSource.h" @interface TableDataSource() @property (nonatomic, strong) NSArray *items; @property (nonatomic, strong) NSString *cellIdentifier; @end @implementation TableDataSource - (id)initWithItems:(NSArray *)items cellIdentifier:(NSString *)cellIdentifier { self = [super init]; if (self) { self.items = items; self.cellIdentifier = cellIdentifier; } return self; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.items.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier forIndexPath:indexPath]; cell.textLabel.text = self.items[indexPath.row]; return cell; } @end
从tableview控制器中,我所要做的就是实例化这个类的一个实例,并将它设置为tableview的数据源,并且它工作得很好。
self.dataSource = [[TableDataSource alloc] initWithItems:@[@"One", @"Two", @"Three"] cellIdentifier:@"Cell"]; self.tableView.dataSource = self.dataSource;
现在我也想在斯威夫特做同样的事。首先这是我的密码。它基本上是上面目标C代码的翻译。
import Foundation import UIKit public class TableDataSource: NSObject, UITableViewDataSource { var items: [AnyObject] var cellIdentifier: String init(items: [AnyObject]!, cellIdentifier: String!) { self.items = items self.cellIdentifier = cellIdentifier super.init() } public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as UITableViewCell cell.textLabel?.text = items[indexPath.row] as? String return cell } }
我就这样叫它。
let dataSource = TableDataSource(items: ["One", "Two", "Three"], cellIdentifier: "Cell") tableView.dataSource = dataSource
但是应用程序崩溃时出现了以下错误。
---NSConcreteNotificationtableView:number OfRowsInSection:*发送到实例的未识别的选择器
为数据源创建一个属性,并与您的表视图一起使用它。
class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var dataSource:TableDataSource! override func viewDidLoad() { super.viewDidLoad() dataSource = TableDataSource(items: ["One", "Two", "Three"], cellIdentifier: "Cell") tableView.dataSource = dataSource } }