gpt4 book ai didi

c# - UINib 的 Xamarin DequeueReusableCell 始终生成 null

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:20:40 25 4
gpt4 key购买 nike

我创建了一个简单的 View Controller ,上面有一个 TableView 。然后我创建了一个 .xib 文件来设计将进入表格的 UITableViewCells。

无论我如何尝试 GetCell 都找不到 UITableViewCell Nib 。我已经检查了名称/ID 和转换的所有变体。我是 Xamarin 和 C# 的新手,所以我可能遗漏了一些简单的东西。

View Controller :

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.
}
}

WorkCell .xib 文件

enter image description here

enter image description here

表格 View 数据源:

    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( 选择 iOS,选择 Table View Cell)

  • 在您的 ViewController 子类中注册用于单元重用的 nib

  • 设置reuse identifier(为简单起见,使用与cell名称相同的名称即可)

  • 当单元格出队时使用重用标识符

注册 Nib

ViewDidLoad 的 UITableViewController 子类中(例如,在设置 DataSource 之前)添加以下内容:

table.RegisterNibForCellReuse(WorkCell.Nib, WorkCell.Key);

为单元格设置重用标识符

reuse identifier

出列 Cell

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;
}

在模拟器中测试

test in simulator

关于c# - UINib 的 Xamarin DequeueReusableCell 始终生成 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53509339/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com