将UIButton放在tableView中

时间:2019-01-30 18:06:53

标签: swift uitableview uibutton

我编写了一个代码,用于在TableView中添加一个UIView数组,但是当我添加它们时,它并没有逐行显示它们,而我循环了一次,将其添加到TableView中的每个项目,但是它添加了它们一个高于另一个,另一个解决方案?

我的视图控制器:

class mainViewController: UIViewController {

  private var myArray: [UIView] = []
  private var myTableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
    let barHeight: CGFloat = UIApplication.shared.statusBarFrame.size.height
    let displayWidth: CGFloat = self.view.frame.width
    let displayHeight: CGFloat = self.view.frame.height

    myTableView = UITableView(frame: CGRect(x: 50, y: barHeight, width: displayWidth, height: displayHeight - barHeight))
    myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
    myTableView.dataSource = self
    myTableView.delegate = self
    self.view.addSubview(myTableView)

    let DoneBut: UIButton = UIButton(frame: CGRect(x: 50, y: 0, width: 150, height: 50))
    DoneBut.setTitle("Done", for: .normal)
    DoneBut.backgroundColor = UIColor.blue

    let DoneBut2: UIButton = UIButton(frame: CGRect(x: 50, y: 0, width: 50, height: 50))
    DoneBut2.setTitle("Done2", for: .normal)
    DoneBut2.backgroundColor = UIColor.blue

    let view1 = UIView()
    view1.addSubview(DoneBut)
    myArray.append(view1)

    let view2 = UIView()
    view2.addSubview(DoneBut2)
    myArray.append(view2)
}

}

extension mainViewController: UITableViewDataSource {
 func tableView(_ tableView: UITableView, cellForRowAt indexPath: 
  IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: 
    "MyCell", for: indexPath as IndexPath)
    for array in myArray {
        cell.contentView.addSubview(array)
    }
    return cell
 }

 func tableView(_ tableView: UITableView, numberOfRowsInSection 
 section: Int) -> Int {
    return myArray.count
 }
}
extension mainViewController: UITableViewDelegate {
 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: 
 IndexPath) {
    print("Num: \(indexPath.row)")
    print("Value: \(myArray[indexPath.row])")
 }
}

1 个答案:

答案 0 :(得分:1)

您的问题是,每次cellForRowAt函数要求一个单元格时,您都在遍历所有视图并将它们添加到每个单元格中。相反,您应该使用indexPath在其中建立索引。请参阅以下内容:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath as IndexPath)

    // check if there is a view at the indexPath
    if indexPath.row < myArray.count {
        // there is a view, add it to the cells contentView
        cell.contentView.addSubview(myArray[indexPath.row])
    } else {
        print("no view at index")
    }

    return cell
}