Adding multiple custom cells in UITableView

后端 未结 2 1113
悲&欢浪女
悲&欢浪女 2021-02-09 00:08

Though this is one of the most asked question but i could not find one comprehensive answer. I need to have custom cells in UITableView. Some containing labels or text fields an

2条回答
  •  星月不相逢
    2021-02-09 00:29

    Add UITableView To UIView.Add custom cells, associate custom cell classes and implement delegates -UITableviewDelegate and UITableViewDataSource .

    case 1: Two custom cells on tableview

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

      var cell: CustomCell!
    
      if indexPath.row == 0{
        cell = tableView.dequeueReusableCellWithIdentifier("Cell1ID", forIndexPath: indexPath) as CustomCell
        //set cell2
      }
      if indexPath.row >= 1{
        cell = tableView.dequeueReusableCellWithIdentifier("Cell2ID", forIndexPath: indexPath) as CustomCell
        let cons = aArray[indexPath.row - 1]
        // set cell2 
      }
      return cell
    }
    

    case 2: alternate display of custom cells (i.e. using uisegmentcontrol)

    var CellIdentifier: String = "Cell1ID"
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
           if (CellIdentifier == "Cell1ID")
        {
    let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier)! as! FirstTableViewCell
    
    //additional code
    return cell
    
    }
    else {
    let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier)! as! SecondTableViewReportsCell
    
    //Additional code
    
    return cell
    }
    }
    

    case 3: Alternate custom cells (i.e., odd even)

    var CellIdentifier: String = "Cell1ID"
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
    var cell: CustomCell!
    
    if (indexPath.row % 2 == 0) {
    
    let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier)! as! FirstTableViewCell
       
    }
    else
    {
            let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier)! as! SecondTableViewCell
    }
    return cell
    }
    

提交回复
热议问题