简体   繁体   中英

Second tableview in UITableViewController

In my storyboard, I have a UITableViewController with static cell and 4 sections.

  • Section 1 with 6 rows and 1st row height is much higher than others.
  • Section 2 with 1 row.
  • Section 3 with 4 rows.
  • Section 4 with 1 row.

In the row of Section 4, I added into a UITableView (table2) with dynamic cell (no header, 1 section only).

So I followed some posts, and had some codes below:

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    if tableView == table2 {
        return 1
    }
    return super.numberOfSectionsInTableView(tableView)
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if tableView == table2 {
        return 4
    }
    return super.tableView(tableView, numberOfRowsInSection: section)
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    if tableView == table2 {
        let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as! CustomerCellView
        cell.setCustomCell()
        return cell
    }
    return super.tableView(tableView, cellForRowAtIndexPath: indexPath)
}

When run it, it builds successfully. The default table shows correctly, but table2 does not. table2 seemed to follow the format of the default table, so the problems are

  • table2 also shows the same header as the first header of default table, even I did not set.
  • If I set the number of rows greater than 6, the app crashed in the simulator.
  • I put the breakpoint at tableView == table2 , the complier did goes into the if statement
  • table2 delegate and datasource are connected to the UITableViewController itself.

If anyone knows what problem my code has, or anyone knows how to add a second tableview in UITableViewController

After a day, I figured out a way to solve this problem. Inspired by these posts:

So instead of putting a UITableView in the static cell, I put a Container View inside of the cell (in my case, the first row of Section 4), which embedded to another UITableViewController or UIViewController depends on your needs. The corresponding tableview codes go to another new file. And the way to set up the new table is as usual.

You would have to create an uiviewcontroler and add 2 table views in that view. Then you can link them to the view controller with the data source and delegate. Then add the delegate in the view controllers class. After add in the normal functions for a table view.. You can use reeuse identifyers to classify which one needed.

Best of luck, Aj

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