我知道我们可以在Objective C中的一个xib下加载多个uitableview单元格,但它是否也可以在
swift中加载?
我尝试使用在Objective C中使用的相同逻辑
var cellAuditDetails:AuditDetailsTableViewCell! = tableView.dequeueReusableCellWithIdentifier("customTrialDetailsCell",forIndexPath: indexPath) as! AuditDetailsTableViewCell if indexPath.row == 0{ if(cellAuditDetails == nil) { cellAuditDetails = NSBundle.mainBundle().loadNibNamed("AuditDetailsTableViewCell",owner: self,options: nil)[0] as! AuditDetailsTableViewCell; } } else{ cellAuditDetails = NSBundle.mainBundle().loadNibNamed("AuditDetailsTableViewCell",options: nil)[1] as! AuditDetailsTableViewCell; }
但得到以下错误***由于未捕获的异常’NSInternalInconsistencyException’终止应用程序,原因:’无效的nib注册为标识符(customTrialDetailsCell) – nib必须包含一个必须是UITableViewCell实例的顶级对象’
现在,如果我只使用一个细胞,那就好了.但是如何在同一个xib下加载多个单元格呢?因为每个新细胞都需要另外一个xib.
解决方法
如果您区分XIB中的视图(标签,自定义类等),那么您甚至不需要注册笔尖 – 您只需要这样做:
override func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cellIndex = 12345 var cellIdentifier = "MyAwesomeCell" // dequeue cell or,if it doesn't exist yet,create a new one from the nib var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)! if !cell { var topLevelObjects = Bundle.main.loadNibNamed("MyNibWithLotsOfCustomCells",options: nil) var index = (topLevelObjects as NSArray).indexOfObject(passingTest: {(_ obj: Any,_ idx: Int,_ stop: Bool) -> BOOL in // if you distinguish the views by class return type(of: obj) === NSClassFromString(cellIdentifier) // if you distinguish the views by tag return (obj as! UIView).tag == cellIndex }) cell = topLevelObjects[index] } }
还有一件事要记住使用
dequeueReusableCell(withIdentifier:cellIdentifier)
代替
dequeueReusableCell(withIdentifier: cellIdentifier,for: indexPath)