• 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) } }



  • 相关阅读:
    1337:【例3-2】单词查找树
    1336:【例3-1】找树根和孩子
    1301:大盗阿福
    CSP-J/S 第一轮知识点选讲
    【转】C++STL各容器的操作及复杂度
    如何查看SUSE的版本信息
    野人和传教士过河问题的C语言源代码
    ubuntu如何安装软件
    Heavy Transportation POJ
    Heavy Transportation POJ
  • 原文地址:https://www.cnblogs.com/yangykaifa/p/6736819.html
Copyright © 2020-2023  润新知