在我的iPhone应用程序中,我有一个UIViewController,它有一个UITableView和另一个UIView,在它的xib文件中,xib的 View 包含UITableView和另一个UIView。两个 View 都作为 IBOutlet 链接到 xib 文件中的相应 View 。 当我想以编程方式为 UITableView 设置数据源时,我在 UIViewController 中创建如下方法:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil tableDataSource:(id)dataSource{
if ((self = [self initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
// Custom initialization
self.inventoryTableView.dataSource = dataSource;
//[self.inventoryTableView reloadData];
}
return self;}
然后我在我的另一个类中实现以下方法,我们称之为 B:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
最后,我分配+init B 并将实例传递给创建 UIViewController 的方法 initWithNibName:bundle:tableDataSource:
。所有 View 都出现在模拟器中,但数据源方法似乎没有被调用。
我对另一个 Controller 做了类似的事情并且有效,但它是一个 UITableViewController 而 TableView 是 Controller 的 View 。作为 subview ,我是否必须使用与 initWithNib 不同的另一种方法设置数据源?
更新:
通过将数据源分配放入 viewDidLoad: 方法中,我能够解决这个问题。在我看来,即使在调用 [self initWithNibName:nibNameOrNil bundle:nibBundleOrNil]
之后,主视图的 subview 也没有正确初始化
最佳答案
看看这个答案,我认为它与您建议使用“B”作为 Controller 的外部数据源的建议类似。
Simple way to separate UITableview datasource and delegate from main UIViewController class?
关于iphone - UITableView:以编程方式设置数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3371448/