• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

swift的UITableView的使用

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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




鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
第一次接触swift苹果语言发布时间:2022-07-13
下一篇:
AppCode 2016.2.3 发布,支持 Swift3 的特性发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap