Search code examples
xamarin.iosnullreferenceexceptionmonotouch.dialogdetailtextlabel

MonoTouch - changing DetailTextLabel text color is causing a NullReferenceException error


I am trying to finish up a custom cell for my tables using monotouch.dialog, and have nearly everything sorted out, except for my cell's detail text label colour.

I am overriding GetCell to customise my EntryElement cell like this:

public class CustomStyledEntryElementPlain : MonoTouch.Dialog.EntryElement
{
    public CustomStyledEntryElementPlain (string _caption, string _value) : base(string.Empty,string.Empty,string.Empty,false)
    {
        KeyboardType = UIKeyboardType.Default;
        Value = _value;
        ReturnKeyType = UIReturnKeyType.Done;
        Caption = _caption;
    }

    public override UITableViewCell GetCell(UITableView tableView) {
        var cell = base.GetCell(tableView);
        cell.BackgroundColor = Resources.XDarkGrayColor;
        cell.TextLabel.TextColor = Resources.XWhiteColor;
        cell.BackgroundView = new UIView (RectangleF.Empty);
        cell.DetailTextLabel.TextColor = UIColor.White; //this line causes the error

        return cell;
    }
}

I then create the elements like so:

new CustomSection ("Testing"){
                new CustomStyledEntryElementPlain("Test","Test1"),
                new CustomStyledEntryElementPlain("Test","Test2")
            },

However, on displaying the table, I get the error: "System.NullReferenceException has been thrown Object reference not set to an instance of an object"

I could have sworn when I initially prototyped this that I had the DetailTextLabel text color working! Commenting out the change of course results in my table and cell displaying just fine, albeit with black text (which I want to change to white!)

Has anyone got any idea as to why I am getting this?


Solution

  • The DetailTextLabel property in the UITableViewCell is only available if the Cell has a UITableViewCellStyle that supports it. From the UITableViewCell documentation for the DetailTextLabel property:

    UITableViewCell automatically creates the secondary (detail) label if the cell is created with a MonoTouch.UIKit.UITableViewCellStyle that supports a detail label.

    If the cell's style doesn't support a detail label, this property returns null.

    Check the documentation for UITableViewCellStyle to find out which styles support this property.