我试图像这篇文章描述的那样保持我的视图控制器干净 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 tableView:numberOfRowsInSection:]: unrecognized selector sent to instance
我检查了TableDataSource
的init
方法,项目和单元格标识符都被正确传递。我不得不将UITableViewDataSource
方法声明为public
并删除override
关键字,否则它会在编译时出错。
我对发生了什么问题感到困惑。请问有人可以帮帮我吗?
谢谢。
var dataSource: TableDataSource!
并将其赋值给tableview的dataSource
属性,现在它可以工作了 :) 谢谢。 - IsuruUITableView
(以及其他视图/控件)的delegate
和dataSource
属性被声明为unowned
,所以如果它不是视图控制器本身,你需要自己引用委托/数据源。 - Nate CookdataSource
属性的类型时看到了unowned
,但不知道它是什么。谢谢你澄清了这一点。 - Isuru