Reputation: 1408
I'm creating a Xamarin app for iOS and I've added a UITableViewCell to a storyboard to give it my own style. I did add a class to this custom UITableViewCell, namely MainMenuCell. I added two labels to the cell and connected them with the MainMenuCell.h file, resulting in the following code:
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 (auto-generated):
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;
}
}
}
}
Now I have my UITableViewSource here, and I'm trying to initialize the MainMenuCell from the GetCell method:
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;
}
}
}
However, it keeps throwing me a System.NullReferenceException at the line:
projectNameLabel.Text = "Project name";
It says: object reference not set to an instance of an object.
What am I missing here? Any help would be highly appreciated.
Upvotes: 4
Views: 1909
Reputation: 3597
You're almost there – instead of creating a new cell by yourself, let iOS do the work and dequeue the result.
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
var cell = (MainMenuCell)tableView.DequeueReusableCell("MainMenuCell");
cell.SetCellData();
return cell;
}
Note, that "MainMenuCell" is a identifier for the dynamic prototype cell from the Storyboard, you can name it whatever you want, but it has to be the same withing Storyboard and your Datasource.
Upvotes: 6