首页 > 解决方案 > 我无法将子视图添加到 UItableviewcell

问题描述

代码

 import UIKit

 class ViewController: 
 UIViewController,UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 3
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var suma=UITableViewCell()
    var sampleviewpurple=UIView(frame: CGRect(x: suma.frame.width/0, y: 0, width: suma.frame.width/2, height: suma.frame.height))
    sampleviewpurple.backgroundColor=#colorLiteral(red: 0.2196078449, green: 0.007843137719, blue: 0.8549019694, alpha: 1)

    var sampleviewred=UIView(frame: CGRect(x: suma.frame.width/1, y: 0, width: suma.frame.width/2, height: suma.frame.height))
    sampleviewred.backgroundColor=#colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1)



    suma.contentView.addSubview(sampleviewpurple)
    suma.contentView.addSubview(sampleviewred)

    return suma

}




@IBOutlet weak var tab: UITableView!
override func viewDidLoad() {
    super.viewDidLoad()
    tab.dataSource=self
    tab.delegate=self

}

  }

当我尝试将子视图添加到 suma 并返回到委托时,我的表视图仍然是空白的,我正在将有效的数据源返回到数据源,并且还注意到对表视图的引用一切都很好,但是仍然如何我无法将子视图添加到 uitableviewcell

标签: swiftuitableview

解决方案


cellForRowAt函数中,您必须将表格单元格出列,而不是实例化 UITableViewCell:

var suma = tableView.dequeueReusableCell(withIdentifier: "YOUR_CELL_IDENTIFIER")

推荐阅读