斯威夫特无法出队细胞

问题描述:

我创建表视图容易寄存器单元的分机:斯威夫特无法出队细胞

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

您正在注册不同的单元格类名称,并且您将其他类名称取出,我在此处怀疑 – karthikeyan

的错误是在这里

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

您使用VacanciesItem既是类和重用标识符。我假设你的意思

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

,让你与VacanciesItem标识符

+0

您有试过吗?请检查你的代码。 –

+0

什么似乎是这个问题?我假设'VacanciesItem'是重用标识符,'VacanciesCell'是单元类。我错了吗?哪一个是哪个? –

首先,注册VacanciesCell类,在下面的一行代码,什么是key and value pairs指定?

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

要注册一个xib,你需要的,如果你正在使用xib小区指定UINib对象。

考虑,在dctkey("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) 

在迅速,您还需要添加namespace(project name)file name以使其得到识别。

+0

我不使用storyboard或xib,我以编程方式创建单元格。 –

+0

你能展示你如何创建单元格吗? – PGDev

+0

@PGDev“要注册一个xib,你需要指定UINib对象而不是类名。” - [你可以用xib或者一个类来注册一个单元格](https://developer.apple.com/documentation/uikit/uitableview/1614888-register) –