Swift:Static UITableViewCell中的TableView

Yic*_*man 0 uitableview ios swift

我有一个UITableViewController约五个不同的静态细胞.在其中一个单元格中,我试图加载动态UITableView

在界面构建器中,我标记了主UITableViewController tableView0,然后我标记了动态tableView1.

每次我尝试加载控制器时都会崩溃.这是我到目前为止的粗略代码:

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

}
Run Code Online (Sandbox Code Playgroud)

所以我需要知道是否可以在静态tableviewcells中嵌入动态表视图,以及如何做到这一点.

rde*_*mar 5

至于我可以通过试验来确定,你不能使用相同的UITableViewController作为两个表视图的数据源和委托.使用静态表视图,您根本不应该实现数据源方法.奇怪的是,即使我断开数据源并委托我的静态表视图和表视图控制器之间的连接,该表视图仍然在我的表视图控制器类中调用numberOfRowsInSection.如果我在代码中将数据源显式设置为nil,则会阻止它调用数据源方法,但嵌入式动态表视图也无法调用它们,因此这种结构不起作用.

但是,您可以通过使用其他对象作为嵌入式动态表视图的数据源和委托来解决此问题.为嵌入式表视图创建一个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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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