斯威夫特无法将一个细胞出列

时间:2017-07-24 12:15:23

标签: ios swift uitableview

我为表视图创建了一个扩展,以便于注册单元格:

extension UITableView {

    func mapTableViewWithCellsDictionary(dictionary : [String : String]) -> Void {

        for (key, _) in dictionary {
            self.register(NSClassFromString(dictionary[key]!), forCellReuseIdentifier: key)
        }

    }
}

在我的视图控制器中,我做了:

  let dct = ["VacanciesItem":"VacanciesCell"]
        tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
        tableView.separatorStyle = .none
        tableView.mapTableViewWithCellsDictionary(dictionary: dct)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.estimatedRowHeight = 80
        tableView.rowHeight = UITableViewAutomaticDimension
        self.view.addSubview(tableView)

然后:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


    let cell : ModelBinding  = tableView.dequeueReusableCell(withIdentifier: "VacanciesItem", for: indexPath as IndexPath) as! ModelBinding
    cell.bindWithModel(model: self.viewModel.arrValues[indexPath.row])

    return cell as! UITableViewCell
}

然而,应用程序无法看到该单元格,它会引发错误:

'unable to dequeue a cell with identifier VacanciesItem - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

但我已经注册了它。

3 个答案:

答案 0 :(得分:1)

错误在这里

for (key, _) in dictionary {
        self.register(NSClassFromString(dictionary[key]!), forCellReuseIdentifier: key)
    }

您正在使用VacanciesItem作为类和重用标识符。我认为你的意思是

for (key, value) in dictionary {
        self.register(NSClassFromString(dictionary[value]!), forCellReuseIdentifier: key)
    }

这样您就可以使用VacanciesCell标识符注册VacanciesItem

答案 1 :(得分:0)

首先,在下面的代码行中,key and value pairs指定了什么?

  let dct = ["VacanciesItem":"VacanciesCell"]

要注册xib,如果您使用UINib制作单元格,则需要指定xib对象。

考虑到,在dct中,key("VacanciesItem")xib namevalue("VacanciesCell")cell identifier

   func mapTableViewWithCellsDictionary(dictionary : [String : String]) -> Void
   {
            for (nibName, identifier) in dictionary
            {
                self.register(UINib(nibName: nibName), forCellReuseIdentifier: identifier)
            }
   }

如果您使用代码创建UITableViewCell,那么要注册它使用:

    let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String;
    self.tableView.register(NSClassFromString("\(namespace).\(nibName)") as? UITableViewCell.Type, forCellReuseIdentifier: identifier)

在swift中,您还需要添加namespace(project name) file name来识别它。

答案 2 :(得分:0)

请按以下说明更改扩展名

extension UITableView {

    func mapTableViewWithCellsDictionary(dictionary : [String : String]) -> Void {

        for (key, _) in dictionary {
            self.register(UINib(nibName: String(describing:dictionary[key]!), bundle: nil), forCellReuseIdentifier: key)
        }

    }
}
相关问题