我正在使用 Xamarin.iOS 构建 iOS 应用程序。我正在使用情节提要,并UITableViewController
使用自定义单元格创建了一个带有分组表的表格。该单元格包含我要为其分配值的标签。
覆盖数据源中的 getcell 方法来设置标签的 text 属性会引发空异常,我找不到原因?我检查了插座,它就在那里。关于如何找到错误的任何提示?
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?
}
}