Reputation: 1174
I'm trying follow some examples for creating a custom UITableViewCell in Xamarin.iOS and all of the examples out there pretty much say the same thing and use the same code, but I can't get it working. Below is my GetCell method on my custom UITableViewSource:
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
var cell = tableView.DequeueReusableCell(CellIdentifier) as WorkoutPhaseListViewCell;
if (cell == null)
{
cell = new WorkoutPhaseListViewCell();
var views = NSBundle.MainBundle.LoadNib("WorkoutPhaseListView", cell, null);
cell = (WorkoutPhaseListViewCell)ObjCRuntime.Runtime.GetNSObject(views.ValueAt(0));
}
WorkoutPhase item = WorkoutPhases[indexPath.Row];
return cell;
}
No matter what I do, the call to cast the ObjCRuntime.GetNSObject is always null (or, in this case throws an invalid cast exception because I'm not using the as keyword on purpose to illustrate the point) because it can't be cast to my custom type (which is subclassing UITableViewCell). It seems to be a problem with casting the value from NSObject to my managed type.
Here is one of the examples I'm trying to follow.
Is there some special magic that I'm missing to be able to cast the NSObject to my type?
Upvotes: 0
Views: 465
Reputation: 1174
It turns out a refactor using Xamarin Studio cased my problem. I changed the name to WorkoutPhaseListViewCell from WorkoutPhaseListView and XS didn't change the [Register] attribute in the .designer.cs file, so my type was not the type it was supposed to be at runtime.
Upvotes: 1
Reputation: 43553
views.ValueAt(0)
That can be dangerous assumption as a change elsewhere (e.g. in the NIB file) in your project can break your code. Adding some (debug-only) checks might save you a lot of future (or present) trouble.
For the InvalidCastException
use the debugger to identify what's in position 0
of your views
(which is an NSArray
). If it's not an WorkoutPhaseListViewCell
(e.g. an UIView
inside it) then the cast exception is normal.
Also make sure your NIB has the right identifier set (to match the code) and that you have a [Register]
on your managed WorkoutPhaseListViewCell
type.
Upvotes: 0