RxSwift绑定UITableView报错:Generic parameter 'Self' could not be inferred
解决RxSwift绑定UITableView时的
Generic parameter 'Self' could not be inferred错误 这个错误我之前也碰到过,大概率是RxSwift的API版本差异或者类型推断的小问题,给你几个可行的解决办法:
1. 适配RxSwift新版本的API
如果你用的是RxSwift 4.0及以上的版本,bindTo已经被官方废弃,推荐使用bind(to:);同时addDisposableTo也更新为disposed(by:)。把你的代码改成下面这样,基本就能解决问题:
let countries = Observable.just(countryArray) countries.bind(to: tableView.rx.items(cellIdentifier: "myCell", cellType: MyCell.self)) { row, country, cell in // 这里写你的cell配置逻辑,比如: cell.textLabel?.text = country } .disposed(by: disposeBag)
2. 手动复用Cell,帮助编译器推断类型
如果上面的方法还是不行,可以换一种items的调用方式,手动获取复用Cell,让编译器更清晰地识别类型:
let countries = Observable.just(countryArray) countries.bind(to: tableView.rx.items) { tableView, row, country in guard let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as? MyCell else { fatalError("无法获取MyCell类型的复用Cell") } cell.textLabel?.text = country return cell } .disposed(by: disposeBag)
3. 检查基础配置是否正确
最后再确认两个关键细节:
- 你的
MyCell类已经正确关联到Storyboard/XIB中的Cell,并且重用标识符完全匹配为myCell(大小写一致)。 - 你的
disposeBag是正确的DisposeBag实例,不是自定义类型或者nil。
内容的提问来源于stack exchange,提问作者Litle Dev
相关产品推荐
相关产品推荐

