问题
I have UITableViewSource
class which is used for the UISearchDisplayController
. In my main table view I have a custom cell which works fine. Now I want to use the custom cell also for the table view of the search results. But I only manage it to display the default style with
public class SearchSource : UITableViewSource
{
static NSString cellIdentifier = new NSString("CustomCell");
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
UITableViewCell cell = tableView.DequeueReusableCell (cellIdentifier);
if (cell == null)
cell = new UITableViewCell (UITableViewCellStyle.Default, cellIdentifier);
cell.TextLabel.Text = myList [indexPath.Row].Name;
return cell;
}
But here I only have the standard cell and I want my custom cell. The custom cell on the main table view uses the following code:
public partial class TestViewController : UITableViewController
{
static NSString cellIdentifier = new NSString("CustomCell");
public TestViewController (IntPtr handle) : base (handle)
{
TableView.RegisterClassForCellReuse (typeof(CustomCell), cellIdentifier);
}
public class TableSource : UITableViewSource {
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath){
CustomCell cell = (CustomCell)tableView.DequeueReusableCell (cellIdentifier);
cell.UpdateCell(...);
}
}
Here is the constructor of the CustomCell
:
public CustomCell (IntPtr handle) : base(handle)
This is how I create the UISearchDisplayController
:
// create search controller
searchBar = new UISearchBar (new RectangleF (0, 0, View.Frame.Width, 50)) {
Placeholder = "Enter a search query"
};
searchController = new UISearchDisplayController (searchBar, this);
searchController.Delegate = new SearchDelegate (tableItems);
searchController.SearchResultsSource = new SearchSource (searchController);
this.TableView.TableHeaderView = searchBar;
But everything I try leads to a crash of the app (no reference, cannot dequeue, ...) or there is a constructor mismatch.
How can I use my custom cell for the table view generated by the UISearchDisplayController
?
回答1:
Switching to the new cell reuse pattern since iOS 6 I adapted my SearchSource
to
CustomPatientCell cell = (CustomCell)tableView.DequeueReusableCell (cellIdentifier);
and I added the following to my TestViewController
:
searchController.SearchResultsTableView.RegisterClassForCellReuse(typeof(CustomCell), cellIdentifier);
I only had to add some methods like GetHeightForRow
to my SearchSource
to get this thing to work.
Now I have two similar implementations of TableSource
and SearchSource
- perhaps it is possible to summarize both? I saw from other implementations that methods like numberOfRowsInSection
query which table view is currently active. How could I summarize that also?
来源:https://stackoverflow.com/questions/25306895/how-to-make-use-of-cell-reuse-in-uitableviewsource-in-xamarin