如何使用静态单元格创建UItableViewContoller并将带有原型单元格的UITableView插入其中一个静态单元格中?

时间:2016-07-29 09:25:58

标签: ios swift xcode uitableview nested

  1. 有可能完成吗?即使不推荐
  2. 如果有可能,我该怎么做呢?
  3. 如果你知道一种方法 - 请尽可能详细说明:)

    我正在研究Swift,所以Obj-C并没有真正帮助

    感谢所有花时间阅读和回答的人

1 个答案:

答案 0 :(得分:2)

首先从故事板开始,这是tableViewController的层次结构。见下图。

enter image description here

之后创建一个UITableViewCell类来保存第二个表视图并将该类分配给第二个表视图单元格。如下。

import UIKit
class tableTableViewCell: UITableViewCell, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        tableView.delegate = self
        tableView.dataSource = self
    }

    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 5
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
         let cell = tableView.dequeueReusableCellWithIdentifier("dynamicCell")!
         cell.textLabel?.text = "\(indexPath.row)"
         return cell
    }
}

enter image description here

然后在tableViewController中使用cellForRow方法初始化单元格并根据需要返回单元格。

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return 2
}

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    if indexPath.row == 0 {
        return 50
    } else {
        return 200
    }
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    if indexPath.row == 0 {

        let cell = tableView.dequeueReusableCellWithIdentifier("staticCell", forIndexPath: indexPath)
        return cell
    } else {
        let cell = tableView.dequeueReusableCellWithIdentifier("tableCell")! as! tableTableViewCell
        return cell
    }

    // Configure the cell...
}

就是这样。干得好。以下是上述代码的输出。

enter image description here

你可以看到第一个“单元格1”是一个静态单元格,而在第二个单元格下面有另一个tableView,显示数字0-4表示单元格2中第二个tableview的另一个5单元格。

相关问题