简体   繁体   中英

How to add UITableview within Tableview Cell using Swift

In myscenario, I am trying to add Dynamic UITableview within Static UITableview Cell. How to achieve this? I tried below code but It is not working for me.

The dynamic tableview cell count based need to readjust static tableview cell height. Please provide some sample code.

Tableview Code

import UIKit

  class CustomCell: UITableViewCell,UITableViewDataSource,UITableViewDelegate {

  var dataArr:[String] = []
  var subMenuTable:UITableView?
  override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
      super.init(style: style , reuseIdentifier: reuseIdentifier)
      setUpTable()
  }

  required init(coder aDecoder: NSCoder) {
      fatalError("init(coder:) has not been implemented")
      setUpTable()
  }

  override func awakeFromNib() {
      super.awakeFromNib()
      // Initialization code
      setUpTable()
  }

  func setUpTable(){
      subMenuTable = UITableView(frame: CGRectZero, style:UITableViewStyle.Plain)
      subMenuTable?.delegate = self
      subMenuTable?.dataSource = self
      self.addSubview(subMenuTable!)
  }

  override func layoutSubviews() {
      super.layoutSubviews()
      subMenuTable?.frame = CGRectMake(0.2, 0.3, self.bounds.size.width-5, self.bounds.size.height-5)
  }

  override func setSelected(selected: Bool, animated: Bool) {
      super.setSelected(selected, animated: animated)
      // Configure the view for the selected state
  }

  func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      return dataArr.count
  }

  func numberOfSectionsInTableView(tableView: UITableView) -> Int {
      return 1
  }

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

    var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("cellID")

    if cell == nil {
        cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cellID")
    }

    cell?.textLabel?.text = dataArr[indexPath.row]

    return cell!
  }
}

Create a single view project add tableview inside storyboard and set up its datasource and delegate

do code as below to firstViewController.swift

import UIKit

  class firstViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

  override func viewDidLoad() {
      super.viewDidLoad()
            }

  override func didReceiveMemoryWarning() {
      super.didReceiveMemoryWarning()
      // Dispose of any resources that can be recreated.
  }

  func numberOfSectionsInTableView(tableView: UITableView) -> Int {
      return 3;
  }

  func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      return 1;
  }

  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
      var cell:CustomCell? = tableView.dequeueReusableCellWithIdentifier("Cell") as?  CustomCell
      if cell == nil {
         cell = CustomCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
      }
      cell?.dataArr = ["subMenu->1","subMenu->2","subMenu->3","subMenu->4","subMenu->5"]
      return cell! 
   }

   func  tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
       return 150.0
   }
}

create a new file CustomCell.swift which is the subclass of UITableViewCell and do not select with xib this file is without .xib file table and its cell will be created programatically.

do code as below to CustomCell.swift

import UIKit

  class CustomCell: UITableViewCell,UITableViewDataSource,UITableViewDelegate {

  var dataArr:[String] = []
  var subMenuTable:UITableView?
  override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
      super.init(style: style , reuseIdentifier: reuseIdentifier)
      setUpTable()
  }

  required init(coder aDecoder: NSCoder) {
      fatalError("init(coder:) has not been implemented")
      setUpTable()
  }

  override func awakeFromNib() {
      super.awakeFromNib()
      // Initialization code
      setUpTable()
  }

  func setUpTable(){
      subMenuTable = UITableView(frame: CGRectZero, style:UITableViewStyle.Plain)
      subMenuTable?.delegate = self
      subMenuTable?.dataSource = self
      self.addSubview(subMenuTable!)
  }

  override func layoutSubviews() {
      super.layoutSubviews()
      subMenuTable?.frame = CGRectMake(0.2, 0.3, self.bounds.size.width-5, self.bounds.size.height-5)
  }

  override func setSelected(selected: Bool, animated: Bool) {
      super.setSelected(selected, animated: animated)
      // Configure the view for the selected state
  }

  func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      return dataArr.count
  }

  func numberOfSectionsInTableView(tableView: UITableView) -> Int {
      return 1
  }

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

    var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("cellID")

    if cell == nil {
        cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cellID")
    }

    cell?.textLabel?.text = dataArr[indexPath.row]

    return cell!
  }
}

I hope it will work for you ...:)

Do this in your main controller:

  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    if tableView = self.tableView {
      var cell:CustomCell? = tableView.dequeueReusableCellWithIdentifier("Cell") as?  CustomCell
    cell.tableView.delegate = self
    cell.tableView.dataSource = self
      return cell! 
} else {
 var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("cellID")//here you custom cell's tableView's cell
return cell
}

   }

Basically you will have to calculate height of your child tableview as demonstrated below

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
{
    @IBOutlet weak var parentTableView : UITableView? = nil
    var sections = [[String:[[String:String]]]]()

    override func viewDidLoad()
    {
        super.viewDidLoad()
        setup()
    }

    func setup()
    {
        // Data
        let section1 = ["Items" : [["Title" : "Row 1"], ["Title" : "Row 2"]]]
        let section2 = ["Items" : [["Title" : "Row 1"], ["Title" : "Row 2"], ["Title" : "Row 3"]]]
        let section3 = ["Items" : [["Title" : "Row 1"], ["Title" : "Row 2"], ["Title" : "Row 3"], ["Title" : "Row 4"]]]
        sections.append(section1)
        sections.append(section2)
        sections.append(section3)

        // Register header
    }

    func numberOfSections(in tableView: UITableView) -> Int
    {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return sections.count
    }


    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
    {
        // Calculate the height of parent cell.

        var cellHeight : CGFloat = 0.0

        let aSection = sections[indexPath.row]

        if let items = aSection["Items"]
        {
            cellHeight = CGFloat(44 * items.count)
        }

        return cellHeight
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        if let cell  = tableView.dequeueReusableCell(withIdentifier: "ParentTableViewCell") as? ParentTableViewCell
        {
            if let aSection = sections[indexPath.row] as? [String:[[String:String]]], let items = aSection["Items"]
            {
                cell.configure(items: items)
            }

            return cell
        }

        return UITableViewCell()
    }
}

Here is the link for the code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM