UIViewController中使用dataSource与delegate

本文深入解析Swift中UISearchController的使用方法,通过对比苹果示例代码与自定义ViewController的实现,详细阐述了如何正确配置搜索控制器,包括初始化、代理设置及dataSource的必要性。文章指出,在UIViewController而非UITableViewController作为根视图控制器时,需额外设置dataSource,以确保search的TableView能正常获取数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

苹果的示例代码:

@implementation APLMainTableViewController

- (void)viewDidLoad {
	[super viewDidLoad];

    _resultsTableController = [[APLResultsTableController alloc] init];
    _searchController = [[UISearchController alloc] initWithSearchResultsController:self.resultsTableController];
    self.searchController.searchResultsUpdater = self;
    [self.searchController.searchBar sizeToFit];
    self.tableView.tableHeaderView = self.searchController.searchBar;
   
    self.resultsTableController.tableView.delegate = self;
    self.searchController.delegate = self;
    self.searchController.dimsBackgroundDuringPresentation = NO; // default is YES
    self.searchController.searchBar.delegate = self; // so we can monitor text changes + others
    
    self.definesPresentationContext = YES;  // know where you want UISearchController to be displayed
}

我的代码:

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _resultsTableController = [[UITableViewController alloc] init];
    _searchController = [[UISearchController alloc] initWithSearchResultsController:self.resultsTableController];
    self.searchController.searchResultsUpdater = self;
    [self.searchController.searchBar sizeToFit];
    tableView.tableHeaderView = self.searchController.searchBar;

    self.resultsTableController.tableView.delegate = self;
    self.resultsTableController.tableView.dataSource = self;
    self.searchController.delegate = self;
    self.searchController.dimsBackgroundDuringPresentation = NO;
    self.searchController.searchBar.delegate = self;

多出一行:

self.resultsTableController.tableView.dataSource = self;

没有此行时不报错,但一直没有数据,search的TableView不会从此Controller获取数据。

因为APLMainTableViewController继承的UITableViewController,而我的ViewController继承的是UIViewController,需要设置dataSource。

转载于:https://my.oschina.net/u/2315603/blog/386554

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值