Swift:静态UITableViewCell中的TableView

我有一个UITableViewController约五个不同的静态单元格。 在这些单元格之一,我试图加载一个dynamic的UITableView

在界面生成器我标记主UITableViewController的 tableView0 ,然后我标记dynamictableView1

每次尝试加载控制器时,都会崩溃。 这是我迄今为止的粗略代码:

 override func numberOfSectionsInTableView(tableView: UITableView) -> Int { switch tableView.tag { case 0: return 2; case 1: return 1; default: break; } return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch tableView.tag { case 0: return 5; case 1: return 2; default: break; } return 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ComboInfoCell", forIndexPath: indexPath) as! UITableViewCell if tableView.tag == 1 { // Honestly not sure how to configure only the reusablecells, and not affect the static cells } return cell } 

所以我需要知道是否可以在静态tableviewcell中embeddeddynamictableviews,以及如何做到这一点。

据我所知,通过对此的实验可以确定,不能使用与两个表视图的数据源和委托相同的UITableViewController。 有了静态表格视图,你根本不应该实现数据源方法。 奇怪的是,即使我断开数据源和委托我的静态表视图和表视图控制器之间的连接,该表视图仍然在我的表视图控制器类中调用numberOfRowsInSection。 如果我明确地将代码中的数据源设置为nil,则会阻止它调用数据源方法,但embedded的dynamic表视图也无法调用它们,所以此结构不起作用。

但是,您可以通过使用不同的对象来成为embedded式dynamic表视图的数据源和委托来解决此问题。 为您的embedded式表视图创build一个IBOutlet,并将其数据源和委托设置为此新对象(该示例中的类是DataSource,它是NSObject的一个子类)。

 class TableViewController: UITableViewController { @IBOutlet weak var staticTableView: UITableView! @IBOutlet weak var dynamicTableView: UITableView! var dataSource = DataSource() override func viewDidLoad() { super.viewDidLoad() dynamicTableView.dataSource = dataSource dynamicTableView.delegate = dataSource } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.row != 1 { return 44 }else{ return 250 // the second cell has the dynamic table view in it } } } 

在DataSource类中,只需像往常一样实现数据源和委托方法即可。