在填充UITableViewController时,自定义单元格中的标签为null

我使用Xamarin.iOS来构build一个iOS应用程序。 我正在使用故事板,并创build了一个使用自定义单元格的分组表创build一个UITableViewController 。 单元格包含我要为其分配值的标签。

覆盖数据源中的getcell方法来设置标签的文本属性抛出一个空的exception,我找不到为什么? 我检查了出口,它在那里。 任何提示如何find错误?

 public partial class NameListScreen : UITableViewController { MyTableSource _source = null; public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); LoadNameList(); } void LoadNameList () { var service = new MyService(); var names = service.GetAllNames(); _source = new MyTableSource(names); this.TableView.Source = _source; } } public class MyTableSource : UITableViewSource { protected List<string> _names; protected string _cellIdentifier = "MyCell"; public MyTableSource (List<string> items) { _names = items; } public override int RowsInSection (UITableView tableview, int section) { return _names.Count; } public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath) { // Request a recycled cell to save memory var cell = (MyTableCell) tableView.DequeueReusableCell(_cellIdentifier); // If there are no cells to reuse, create a new one if (cell == null) cell = new MyTableCell(); cell.UpdateCell(indexPath, _names[indexPath.Item]); return cell; } } public partial class MyTableCell : UITableViewCell { public MyTableCell () : base () { } public MyTableCell (IntPtr handle) : base (handle) { } public void UpdateCell(NSIndexPath indexPath, string name) { this._indexPath = indexPath; this._id = track.TrackId; this.NameLabel.Text = name; //This row throws exception as NameLabel is null, why? } } 

基于你的问题,我想你没有以正确的方式加载xib。 在你的自定义单元格里面放置一个如下所示的静态方法。

 // Inside MyTableCell public static MyTableCell Create() { NSArray topLevelObjects = NSBundle.MainBundle.LoadNib("MyTableCell", null, null); MyTableCell cell = Runtime.GetNSObject(topLevelObjects.ValueAt(0)) as MyTableCell; return cell; } 

现在在新的Xamarin单元格创build模板中使用此模式。 唯一的区别是使用UINib类(我无法validation它,因为我没有Xamarin Studio)。

然后,在GetCell方法中,你应该像下面这样做

 public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath) { // Request a recycled cell to save memory var cell = (MyTableCell) tableView.DequeueReusableCell(_cellIdentifier); // If there are no cells to reuse, create a new one if (cell == null) cell = MyTableCell.Create(); cell.UpdateCell(indexPath, _names[indexPath.Item]); return cell; } 

如果您尚未注册,则需要在.cs [Register("MyTableCell")] 。 您还需要在XIB文件中将devise单元格的types设置为MyTableCell

但是,用Xa​​marin模板玩一下(如果你创build一个新的iOS文件,你可以select它们),你会发现一个自定义的单元格模板。