2015-04-03 50 views
2

我正在为iOS创建一个Xamarin应用程序,并且我已经为故事板添加了一个UITableViewCell以给它自己的样式。我没有为这个自定义的UITableViewCell添加一个类,即MainMenuCell。我添加两个标签,以在细胞和与MainMenuCell.h文件连接它们,从而产生以下代码:Xamarin自定义UITableViewCell抛出系统NullReferenceException

MainMenuCell.cs

using System; 
using Foundation; 
using UIKit; 

namespace MyProjectNamespace 
{ 
    public partial class MainMenuCell : UITableViewCell 
    { 
     public MainMenuCell (IntPtr handle) : base (handle) 
     { 
     } 

     public MainMenuCell() : base() 
     { 
     } 

     public void SetCellData() 
     { 
      projectNameLabel.Text = "Project name"; 
      projectDateLabel.Text = "Project date"; 
     } 
    } 
} 

MainMenuCell.h(自动生成的):

using Foundation; 
using System.CodeDom.Compiler; 

namespace MyProjectNamespace 
{ 
[Register ("MainMenuCell")] 
partial class MainMenuCell 
{ 
    [Outlet] 
    UIKit.UILabel projectDateLabel { get; set; } 

    [Outlet] 
    UIKit.UILabel projectNameLabel { get; set; } 

    void ReleaseDesignerOutlets() 
    { 
     if (projectNameLabel != null) { 
      projectNameLabel.Dispose(); 
      projectNameLabel = null; 
     } 

     if (projectDateLabel != null) { 
      projectDateLabel.Dispose(); 
      projectDateLabel = null; 
     } 
    } 
} 
} 

现在我有我的UITableViewSource这里,我试图从GetCell方法初始化MainMenuCell:

using System; 
using UIKit; 
using Foundation; 

namespace MyProjectNamespace 
{ 
public class MainMenuSource : UITableViewSource 
{ 
    public MainMenuSource() 
    { 

    } 

    public override nint NumberOfSections (UITableView tableView) 
    { 
     return 1; 
    } 

    public override string TitleForHeader (UITableView tableView, nint section) 
    { 
     return "Projects"; 
    } 

    public override nint RowsInSection (UITableView tableview, nint section) 
    { 
     return 1; 
    } 

    public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) 
    { 
     MainMenuCell cell = new MainMenuCell(); 
     cell.SetCellData(); 
     return cell; 
    } 
} 
} 

然而,不断抛出我System.NullReferenceException在该行:

projectNameLabel.Text = "Project name"; 

它说:对象引用不设置到对象的实例。

缺少什么我在这里?任何帮助将不胜感激。

回答

6

你快到了 - 不是自己创建一个新的单元,而是让iOS完成工作并将结果出列。

public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) 
{ 
    var cell = (MainMenuCell)tableView.DequeueReusableCell("MainMenuCell"); 
    cell.SetCellData(); 

    return cell; 
} 

注意,认为“MainMenuCell”是从故事板的动态原型电池的标识,你可以命名为任何你想要的,但它必须是相同的withing故事板和您的数据源。

enter image description here

相关问题