ios - 将表数据源设置为某个类时出错

标签 ios swift uitableview tableview

我目前正在学习如何为单个 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/

相关文章:

ios - 单击按钮时在 tableViewCell 中配置数据

iOS:我将我的静态tableView分隔符设置为无,我可以在我的单元格中单独设置我的分隔符吗?

ios - NotificationCenter.default.addObserver 使用 Unwind Segue 多次被调用

ios - 如何显示在后台线程中执行的任务的进度 View

iphone - 如何在 iOS 设备上运行 .app

Swift8 tableview 导出在弹出窗口后变为 nil。 fatal error : unexpectedly found nil while unwrapping an Optional value

iphone - 更新核心数据中的值

ios - UIImageView 未从 ObjectiveC 中的 Superview 中删除

ios - YouTube - 下载/播放私有(private)视频

ios - 如何为 ios-chart 上的每一列添加名称?