【发布时间】:2014-06-30 08:25:02
【问题描述】:
我使用 Xamarin iOS 设计器为我的 TableView 设计自定义 TableViewCell 类。 但所有单元格子视图属性(插座)都返回 null,但单元格本身除外。
我的自定义单元格类:
partial class VehiclesTableCell : UITableViewCell
{
public VehiclesTableCell(IntPtr handle) : base(handle) { }
public void UpdateCell(string licensePlate) {
licensePlateLabel.Text = licensePlate; //hit the null reference exception for licensePlateLabel
}
}
生成的部分类:
[Register ("VehiclesTableCell")]
partial class VehiclesTableCell
{
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UILabel licensePlateLabel { get; set; }
void ReleaseDesignerOutlets ()
{
if (licensePlateLabel != null) {
licensePlateLabel.Dispose ();
licensePlateLabel = null;
}
}
}
以及我的 Table Source 类的 GetCell:
public class VehiclesTableSource : UITableViewSource
{
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) {
// Dequeueing the reuse cell
var cell = (VehiclesTableCell)tableView.DequeueReusableCell(new NSString(typeof(VehiclesTableCell).Name));
// Set cell properties
cell.UpdateCell(LicensePlate);
// Return the cell with populated data
return cell;
}
}
正如我们所见,生成的代码有 licensePlate 的出口,那么为什么它的属性为空? 故事板不应该自动实例化它的所有子视图吗? 至少在所有其他情况下都会发生这种情况。
【问题讨论】:
-
如果在 GetCell 方法中为空,您应该创建单元格。 Check this 他们展示了如何在单元格为空时创建单元格。
-
Cell 不为空,只有它的属性 Labels、ImageViews 等
-
只是想一想,检查 IBOutlets 连接,因为我们没有使用 Xamarin 工作室,因此无法了解 Check this too。
-
@JanakNirmal,通过在控制器中为 TableView 注册的自定义单元格类,可以在 UITableViewSource 的 GetCell 方法中将单元格出列,而无需额外的 null 检查。
TableView.RegisterClassForCellReuse (typeof(MyCell), MyCellId); -
@Tomzie,是的,我愿意。只需在 ViewDidLoad 方法中删除行:
TableView.RegisterClassForCellReuse(typeof(VehiclesTableCell), new NSString("VehicleCell"));即可消除不必要的自定义单元注册。
标签: ios uitableview xamarin.ios xamarin