使用 Storyboard 创建自定义单元格
打开 Storyboard,你有 ViewView 与 TableView:
添加原型单元格(如果之前没有添加单元格):
根据需要自定义单元格(在我的例子中有自定义 UIImage 和 Label):
请记住设置单元格的高度。为此,选择整个 TableView,然后从属性窗口中选择布局选项卡。在属性窗口的顶部,你应该看到行高 - 放入适当的值:
现在再次选择原型单元格。在属性窗口中,键入类的名称(它将为其创建代码隐藏类)。在我的例子中,这是 FriendsCustomTableViewCell
。之后,为你的手机提供标识符。你可以看到我的是 FriendCell
。最后要设置的是 Style
属性设置为 custom。 名称字段应为空。键入 Class
后单击 enter
后,将自动创建代码隐藏文件:
现在,单元格的代码应该如下所示:
public partial class FriendsCustomTableViewCell : UITableViewCell
{
public FriendsCustomTableViewCell (IntPtr handle) : base (handle)
{
}
public FriendsCustomTableViewCell(NSString cellId, string friendName, UIImage friendPhoto) : base (UITableViewCellStyle.Default, cellId)
{
FriendNameLabel.Text = friendName;
FriendPhotoImageView.Image = friendPhoto;
}
//This methods is to update cell data when reuse:
public void UpdateCellData(string friendName, UIImage friendPhoto)
{
FriendNameLabel.Text = friendName;
FriendPhotoImageView.Image = friendPhoto;
}
}
在 UITableViewSource 中,你必须在类的顶部声明 cellIdentifier(在我的情况下是 FriendCell
),在 GetCell
方法中,你必须为它们转换单元格并设置数据:
string cellIdentifier = "FriendCell";
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
FriendsCustomTableViewCell cell = (FriendsCustomTableViewCell) tableView.DequeueReusableCell(cellIdentifier);
Friend friend = _friends[indexPath.Row];
//---- if there are no cells to reuse, create a new one
if (cell == null)
{ cell = new FriendsCustomTableViewCell(new NSString(cellIdentifier), friend.FriendName, new UIImage(NSData.FromArray(friend.FriendPhoto))); }
cell.UpdateCellData(friend.UserName, new UIImage(NSData.FromArray(friend.FriendPhoto)));
return cell;
}