如何在UITableview中使用两个自定义单元格

时间:2018-07-11 05:15:38

标签: ios uitableview swift4

var mutipleArrayForFirstCell:[String] = ["1","2","3","4","5","6","7","8","9","10"]
var mutipleArrayForSecondCell:[String] = ["11","12","13","14","15","16","17","18","19","20"]

//MARK - TableView delegates
func numberOfSections(in tableView: UITableView) -> Int {
    return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 1 {
        return mutipleArrayForFirstCell.count
    }else {
        return mutipleArrayForSecondCell.count
    }  
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if indexPath.row == 0 {
        let valueAt1stCell = tableView.dequeueReusableCell(withIdentifier: "FirstCell", for: indexPath) as! multipleCustomCellTableViewCell
        valueAt1stCell.Firstlabel.text =  mutipleArrayForFirstCell[indexPath.row]

        return valueAt1stCell

    } else {
        let valueAt2ndCell = tableView.dequeueReusableCell(withIdentifier: "SecondCell", for: indexPath) as! SecondCustomTableviewCell
        valueAt2ndCell.secondLabel.text = mutipleArrayForSecondCell[indexPath.row]
        return valueAt2ndCell
    }

}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 100
}

我的问题是我想在两个不同的单元格中显示上面声明的两个数组值。我该怎么做??它显示如下:

enter image description here

但是它应该在一个单元格中显示1-10,而在另一个单元格中显示11-20。请有人帮助我,谢谢!

enter image description here

我如何在两个单元之间留出一些空间?

2 个答案:

答案 0 :(得分:2)

尝试这个

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

switch indexPath.section {
    case 0:
        //First Array
      let valueAt1stCell = tableView.dequeueReusableCell(withIdentifier: "FirstCell", for: indexPath) as! multipleCustomCellTableViewCell
    valueAt1stCell.Firstlabel.text =  mutipleArrayForFirstCell[indexPath.row]

    return valueAt1stCell

    default:
        //Second Array
     let valueAt2ndCell = tableView.dequeueReusableCell(withIdentifier: "SecondCell", for: indexPath) as! SecondCustomTableviewCell
    valueAt2ndCell.secondLabel.text = mutipleArrayForSecondCell[indexPath.row]
    return valueAt2ndCell

    } 
}

答案 1 :(得分:1)

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {        
    if indexPath.section == 0 {
        let valueAt1stCell = tableView.dequeueReusableCell(withIdentifier: "FirstCell", for: indexPath) as! multipleCustomCellTableViewCell
        valueAt1stCell.Firstlabel.text =  mutipleArrayForFirstCell[indexPath.row]
        return valueAt1stCell
    } else {
        let valueAt2ndCell = tableView.dequeueReusableCell(withIdentifier: "SecondCell", for: indexPath) as! SecondCustomTableviewCell
        valueAt2ndCell.secondLabel.text = mutipleArrayForSecondCell[indexPath.row]
        return valueAt2ndCell
    }
}