c# - 在使用 IntPtr 构造函数进行单元重用时设置 Xamarin UITableViewCellStyle

标签 c# ios uitableview xamarin xamarin.ios

根据 this Xamarin docs page ,我正在 Xamarin iOS 应用程序中构建 TableView :

  • 自定义 UITableViewSource 类,覆盖 GetCell()NumberOfSections()RowsInSection()
  • 自定义 UITableViewCell,实现采用 IntPtr 的构造函数以启用单元格重用
  • 在 View Controller 中调用 myTableView.RegisterClassForCellReuse(),为其指定我自定义的 UITableViewCell

这似乎有效。但是,我想使用具有非默认样式的单元格。作为the next page in the docs说明,UITableViewCellStyle 有几个选项,我想使用 UITableViewCellStyle.Value2。现在,UITableViewCell 有一个采用 UITableViewCellStyle 选项的构造函数,但我不能使用它,因为单元格重用需要我实现 IntPtr构造函数,而且我没有看到任何可从内部可用于设置样式的构造函数访问的内容。

有没有办法在不使用 UITableViewCell(UITableViewCellStyle style, NSString reuseIdentifier) 构造函数的情况下选择不同的 UITableViewCellStyle 选项?

最佳答案

我认为不使用 UITableViewCell(UITableViewCellStyle style, NSString reuseIdentifier) 构造函数就不可能加载不同的 UITableViewCellStyle 选项。此构造函数加载底层 XIB。

您提到“非默认样式”,使用您自己的自定义 UITableViewCell 可以让您自由地根据需要设计布局,添加标签、图像等。在 CustomUITableViewCell 内创建一个公共(public)方法,然后您可以定义如何显示内容,如下所述。

UITableView

public class CustomTableView : UITableView
{
    static readonly NSString MyCellId = new NSString ("CustomTableViewCell");

    public CustomTableView ()
    {
        RegisterClassForCellReuse(typeof(CustomTableViewCell), MyCellId);
        Source = new CustomDataSource();
    }
}

UITableViewCell

public class CustomTableViewCell : UITableViewCell
{
    public CustomTableViewCell (IntPtr handle) : base (handle)
    {}

    public Load(object[] data){

        //Create custom view in code

        var title = new UILabel();

        // etc.

        // Or pull in from an XIB

        UINib Nib = UINib.FromName ("CustomViewCell_iPad", NSBundle.MainBundle);
    }
}

UITableViewSource

public class CustomTableDataSource : UITableViewSource
{

    private NSString MyCellId { get; set; }

    public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
    {
        var cell = (CustomTableViewCell)tableView.DequeueReusableCell (MyCellId, indexPath);
        cell.load(sampleData[indexPath.row]);
        return cell;
    }
}

关于c# - 在使用 IntPtr 构造函数进行单元重用时设置 Xamarin UITableViewCellStyle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29917078/

相关文章:

c# - 在子类中使用事件和委托(delegate)

c# - 一组号码中的池号码以匹配另一组号码的大小

ios - 在 Xcode 中使用预处理器处理命令行选项

ios - 带有自定义部分的 UILocalizedIndexedCollat​​ion

iphone - Interface Builder 文件中的未知类 <class_name> - IOS

c# - 以编程方式获取嵌套的静态类名称并访问方法

c# - 在文本框中发生任何更改时立即更改按钮的启用状态?

objective-c - 关于使用 Objective C 编写更多模块化和可测试的 iOS 应用程序的建议

ios - 绘制背景颜色和边框和背景 PNG

ios - TableView 的自定义原型(prototype)单元格