在 StoryBoard 中,我有一个场景包含一些 TextFields、按钮和一个 UITableView。在头文件中声明了 UITableView 的一个实例,但是当我尝试访问方法“cellForRowAtIndexPath”时,我收到以下错误
this class is not key value coding-compliant for the key tableView.
我用谷歌搜索了那个错误,一些结果表明它是关于将 DataSource 和 Delegate 属性链接到 ViewController,但我仍然收到相同的错误
请让我知道如何修复此错误。
代码-1:
-(UITableViewCell *) tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"cellForRowAtIndexPath");
NSString *cellIdentifier = @"cellId";
UITableViewCell *cell = [tableView1
dequeueReusableCellWithIdentifier:cellIdentifier
forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:cellIdentifier];
}
//[cell.textLabel setText: [dataArray
objectAtIndex:indexPath.row]];
if (textFieldRowNameAsString != nil)
cell.textLabel.text = textFieldRowNameAsString;
return cell;
}
代码 2:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITableViewDelegate,
UITableViewDataSource>
{
NSString *textFieldRowNameAsString;
UITableView *tableView1;
UITableViewCell *prototypeCell;
UIView *contentView;
}
image-1:
最佳答案
你可以避免这个错误,如果你
在所有 TableView 数据源和委托(delegate)方法中始终使用传递的 tableView
实例。
而且您不需要检查单元格是否为 nil
,因为此 dequeueReusable
方法始终返回有效的单元格。
由于单元格被重复使用,因此强烈建议始终将所有 UI 元素设置为已定义的状态。
-(UITableViewCell *) tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier = @"cellId";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (textFieldRowNameAsString != nil) {
cell.textLabel.text = textFieldRowNameAsString;
} else {
cell.textLabel.text = ""
}
return cell;
}
PS:如果您想要自定义 TableView 变量/属性,您必须创建一个 IBOutlet
并将 TableView 连接到它。一个简单的属性是不够的。
关于ios - 该类与键 tableView 的键值编码不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44677128/