我目前正在学习如何为单个 tableView 创建多个单元格类型,当我尝试在 Swift 4 中为 UITableView
设置数据源时出现错误。
我收到如下错误信息
Cannot assign value of type 'ProfileViewModel.Type' to type 'UITableViewDataSource?'
我得到这个错误信息的代码是这个
tableView?.dataSource = ProfileViewModel
有关代码的详细信息如下。该类不属于原始的 ViewController
类,但我使用 UITableViewDataSource
声明了该类。
class ProfileViewModel: NSObject, UITableViewDataSource {
var items = [ProfileViewModelItem]()
init(profile: Profile) {
super.init()
guard let data = dataFromFile(filename: "ServerData") else {
return
}
let profile = Profile(data: data)
if let name = profile.fullName, let pictureUrl = profile.pictureUrl {
let nameAndPictureItem = ProfileViewModelNameAndPictureItem(pictureUrl: pictureUrl, userName: name)
items.append(nameAndPictureItem)
}
if let about = profile.about {
let aboutItem = ProfileViewModelAboutItem(about: about)
items.append(aboutItem)
}
if let email = profile.email {
let dobItem = ProfileViewModelEmailItem(email: email)
items.append(dobItem)
}
let attributes = profile.profileAttributes
if !attributes.isEmpty {
let attributesItem = ProfileViewModelAttributeItem(attributes: attributes)
items.append(attributesItem)
}
let friends = profile.friends
if !profile.friends.isEmpty {
let friendsItem = ProfileViewModeFriendsItem(friends: friends)
items.append(friendsItem)
}
}
}
extension ProfileViewModel {
func numberOfSections(in tableView: UITableView) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items[section].rowCount
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// config
}
}
有人能帮帮我吗?
最佳答案
这一行:
tableView?.dataSource = ProfileViewModel
您正在尝试将类型 分配给tableView.dataSource
。 TableView 的数据源不可能是类型,对吧?它应该是符合 UITableViewDataSource
类型的对象。
我想你的意思是
tableView?.dataSource = self
关于ios - 将表数据源设置为某个类时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47854320/