c# - UINib 的 Xamarin DequeueReusableCell 始终产生 null
问题描述
我创建了一个简单的视图控制器,上面有一个表格视图。然后,我创建了一个 .xib 文件来设计将进入表格的 UITableViewCells。
无论我尝试什么GetCell
都找不到 UITableViewCell 笔尖。我经历了名称/身份和演员表的所有变体。我对 Xamarin 和 c# 很陌生,所以我可能缺少一些简单的东西。
视图控制器:
public partial class ScheduleViewController : BaseViewController<ScheduleViewModel>
{
[Export("initWithBundle:owner:extras:")]
public ScheduleViewController(NSBundle bundle, UIViewController owner, string extras) : base("ScheduleViewController", bundle, owner, extras)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
Dictionary<string, List<string>> itemData = new Dictionary<string, List<string>>()
{
{"phones", new List<string>() {
"Android",
"iOS",
"Windows Phone",
"Other",
"The Thing"
}},
{"computers", new List<string>() {
"osx",
"windows",
"linux"
}}
};
UITableView table = new UITableView(View.Bounds);
table.Source = new ScheduleTableViewSource(itemData);
table.SeparatorStyle = UITableViewCellSeparatorStyle.None;
Add(table);
}
UITableVIewCell 类:
public partial class WorkCell : UITableViewCell
{
public static readonly NSString Key = new NSString("WorkCell");
public static readonly UINib Nib;
static WorkCell()
{
Nib = UINib.FromName("WorkCell", NSBundle.MainBundle);
}
protected WorkCell(IntPtr handle) : base(handle)
{
// Note: this .ctor should not contain any initialization logic.
}
}
工作单元 .xib 文件
表视图数据源:
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
// always null
UINib nib = UINib.FromName("WorkCellContainer", NSBundle.MainBundle);
tableView.RegisterNibForCellReuse(nib, "workItemCell");
var cell = (WorkCell)tableView.DequeueReusableCell ("workItemCell");
return cell;
}
解决方案
不需要在 GetCell 方法中加载 nib。要使用 xib 中的自定义单元格,您只需执行以下操作:
使用上下文菜单创建 xib(<Add/New File> 选择
iOS
,选择Table View Cell
)在 ViewController 子类中注册 nib 以供单元重用
设置重用标识符(为简单起见,只需使用与单元名称相同的名称)
当使单元出队时,使用重用标识符
注册笔芯
在您的 UITableViewController 子类中ViewDidLoad
(例如,在设置 DataSource 之前)添加以下内容:
table.RegisterNibForCellReuse(WorkCell.Nib, WorkCell.Key);
为单元设置重用标识符
出列单元格
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
var cell = tableView.DequeueReusableCell(WorkCell.Key, indexPath) as WorkCell;
//set the data in work cell here
return cell;
}
在模拟器中测试
推荐阅读
- eclipse - Eclipse 调试问题
- angular - 根据角度中的用户ID从数据库中获取用户角色
- jquery - 谷歌浏览器在与电话号码无关的文本下拉列表中添加自动填充电话号码
- mysql - 查询联接表上的计数不显示零计数结果
- javascript - Angular js ui-router 跳过 $state.go
- android - 如何通过按下 Android 小部件中的按钮来更改 TextView 的文本
- python - 试图理解代码中的这一行
- python - python函数正在改变一个全局变量
- typescript - 映射类型和通用函数类型错误
- regex - 带有特殊字符 (@) 的 sed/perl