正如本文objc.io Issue #1 Lighter View Controllers中所描述的那样,我正在努力保持视图控制器的整洁。我在Objective-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;
现在我正尝试在Swift中做同样的事情。首先,这是我的代码。它相当于上面的Objective-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
但应用程序崩溃,并出现以下错误。
-NSConcreteNotification表sent :numberOfRowsInSection::发送到实例的无法识别的选择器
我检查了TableDataSource
和items的init
方法,单元格标识符传递得很好。我必须将UITableViewDataSource
方法声明为public
并删除override
关键字,否则会给出编译时错误。
我不知道这里出了什么问题。有谁能帮帮我吗?
谢谢。
https://stackoverflow.com/questions/25788782
复制相似问题