以编程方式创建分组UITableView

use*_*748 6 uitableview grouped-table swift

我有一个UITableViewController,当前显示4个单元格,将始终显示,并希望将它们组合在一起,但我无法弄清楚如何.我发现的资源仅在通过UIViewController或其他类似的东西插入标准UITableView时使用Interface Builder提供指令.如何以编程方式对它们进行分组?

这是我当前的UITableViewController类:

import UIKit

class SecondViewController: UITableViewController {

    let Items = ["Altitude","Distance","Groundspeed"]

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

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
        cell.textLabel?.text = self.Items[indexPath.row]
        return cell
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }

}
Run Code Online (Sandbox Code Playgroud)

prz*_*iak 17

表视图的样式在初始化时设置,以后不能修改,但您可以做的是创建一个具有所需分组样式的新表视图,并将其设置为ViewDidLoad中的表视图:

    self.tableView = UITableView(frame: self.tableView.frame, style: .grouped)
Run Code Online (Sandbox Code Playgroud)

您还应该使用numberOfSectionsInTableView(_ :)在表中指定多个部分,并使用tableView(_:titleForHeaderInSection :)或tableView(_:titleForFooterInSection :)为每个部分指定标题.