Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 将xib视图显示到UITableView单元格中_Swift_Xcode_Uitableview_Addsubview - Fatal编程技术网

Swift 将xib视图显示到UITableView单元格中

Swift 将xib视图显示到UITableView单元格中,swift,xcode,uitableview,addsubview,Swift,Xcode,Uitableview,Addsubview,我在一个名为“ExperienceScreen”的主ViewController中加载的xib文件中创建了一个视图。将此xib视图添加到ExperienceScreen中非常有效。问题是我想在UITableViewCel中添加这个xib视图。我正在使用以下代码来执行此操作: let experiences = service.getExperiences() // 3. Loop through the array of experiences for element

我在一个名为“ExperienceScreen”的主ViewController中加载的xib文件中创建了一个视图。将此xib视图添加到ExperienceScreen中非常有效。问题是我想在UITableViewCel中添加这个xib视图。我正在使用以下代码来执行此操作:

   let experiences = service.getExperiences()


    // 3. Loop through the array of experiences
    for element in experiences {

        if let customView = Bundle.main.loadNibNamed("ExperienceDetail", owner: self, options: nil)?.first as? ExperienceDetail
        {
            customView.lblTitle.text = element.title
            customView.lblCompany.text = element.company
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell
            cell.addSubview(customView)
            cell.bringSubview(toFront: customView)
        }
    }

    tableView.reloadData()
启动时,子视图不会显示在UITableViewCell中。customView视图正确地填充了xib视图。我用断点检查了这个

有人知道我做错了什么


非常感谢你的帮助

不要试图同时设置所有单元格

您应该实现
UITableViewDataSource
协议,并使用
tableView(uu:cellForRowAt:)
方法配置每个单元格。在这个方法中,您可以调用
寄存器(uuquo:forCellReuseIdentifier:)
为新创建的单元格使用XIB


有很多关于创建表视图的教程,您可以在其中找到有关如何创建表视图的分步说明。

如果您希望将xib文件显示为UITableViewCell,则以下方案可行 1.确保您的xib类是UITableViewCell的子类。 2.注册您的xib

//class of xib file
class TableCell: UITableViewCell {
  static let identifier = "TableCell"
  static let nib = UINib(nibName: "TableCell", bundle: nil)
}

// In view controller
func setupTableView() {
 tableView.dataSource = self
 tableView.delefate = self
 tableView.register(TableCell.nib, forCellReuseIdentifier: 
 TableCell.identifier)
}

在viewDidLoad()中调用setupTableView()

谢谢您的回复!不幸的是,它仍然没有显示。您看到我的代码中的问题了吗:在cellForRowAt change let cell=tableView.dequeueReusableCell(带有标识符:“cell”)!as UITableViewCell let cell=tableView.dequeueReusableCell(带标识符:ExperienceDetail.identifier)as!体验详细信息并根据您的需要填充tableCell