swift的UITableView的使用

UITableView是app开发中经常使用到的控件,功能非常强大,多用于数据的显示。

以下以一个简单的实例来介绍其基本使用方法。


先建一个project
代码例如以下:

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    private var dataSource: Dictionary<String, [String]>? //定义表格的数据源
    private var keyArray: [String]?
    private let cellIdef = "zcell"

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //初始化数据
        demoData()
        
        var frame = self.view.bounds
        frame.origin.y += 20
        frame.size.height -= 20
        
        //初始化表格
        var tableView = UITableView(frame: frame, style: UITableViewStyle.Plain)
        //设置重用标志
        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellIdef)
        tableView.tableFooterView = UIView()
        tableView.dataSource = self
        tableView.delegate = self
        self.view.addSubview(tableView)
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }

    private func demoData() {
        dataSource = ["国家": ["中国", "美国", "法国", "德国", "意大利", "英国", "俄罗斯"],
                      "种族": ["白种人", "黄种人", "黑种人"]
                     ]
        keyArray = ["国家", "种族"]
    }
    
    // MARK: - UITableViewDataSource
    
    //设置表格的组数
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return keyArray!.count
    }
    
    //设置表格每组的行数
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var array = dataSource![keyArray![section]]
        return array!.count
    }
    
    //设置表格的内容
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier(cellIdef, forIndexPath: indexPath) as UITableViewCell
        var array = dataSource![keyArray![indexPath.section]]
        cell.textLabel.text = array![indexPath.row]
        return cell
        
    }
    
    //设置每组的标题
    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?

{ return keyArray![section] } //MARK: - UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } }



原文地址:https://www.cnblogs.com/yangykaifa/p/6736819.html