使用 Storyboard 建立自定義單元格

開啟 Storyboard,你有 ViewView 與 TableView:

新增原型單元格(如果之前沒有新增單元格):

根據需要自定義單元格(在我的例子中有自定義 UIImage 和 Label):

StackOverflow 文件

StackOverflow 文件

請記住設定單元格的高度。為此,選擇整個 TableView,然後從屬性視窗中選擇佈局選項卡。在屬性視窗的頂部,你應該看到行高 - 放入適當的值:

StackOverflow 文件

現在再次選擇原型單元格。在屬性視窗中,鍵入類的名稱(它將為其建立程式碼隱藏類)。在我的例子中,這是 FriendsCustomTableViewCell。之後,為你的手機提供識別符號。你可以看到我的是 FriendCell。最後要設定的是 Style 屬性設定為 custom。 名稱欄位應為空。鍵入 Class 後單擊 enter 後,將自動建立程式碼隱藏檔案:

StackOverflow 文件

StackOverflow 文件

現在,單元格的程式碼應該如下所示:

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;
}