swift 4.2代码实现表视图UITableView

表视图的组成

  • 表头视图: 表视图最上边的视图,用于展示表视图的信息,也可以放搜索栏
  • 表脚视图: 表视图最下边的视图,用于展示表视图的信息,例如显示"更多","加载中"
  • 单元格: 是组成表视图每一行的单位视图
  • 节: 由多个单元格组成,有节头和节脚. 节头,描述节的信息,文字左对齐. 节脚,也可描述节的信息和声明,文字左对齐.

表视图的相关类

  • 表视图UITableView继承自UIScrollView
  • 单元格类是UITableViewCell
  • UITableView的控制器是UITableViewController
  • UITableViewHeaderFooterView类用于为节头和节脚提供视图

122666-bac8edf0a68f0749.png
image.png

表视图分类

  • 普通表视图. 主要用于动态表,动态表一般在单元格数目未知的情况下使用,是展示动态数据的表.
  • 分组表视图. 可用于动态表和静态表(静态表一般用于控件的界面布局). 动态表分组时,单元格分成不同部分, 而每一部分中单元格中的数据是类似的.
  • 此外,表视图中还可以带有索引列,选择列和搜索栏等.

单元格的组成和样式

122666-b1911187d963ed20.png
image.png

标准单元格样式是在枚举类型UITableViewCellStyle中定义的.

扩展视图可以内置或者自定义. 内置的扩展视图是在枚举类型UITableViewCellAccessoryType中定义.


viewcontroller.swift代码:

import UIKit

let CellIndentifier = "CellIdentifier"

class ViewController: UIViewController , UITableViewDelegate,UITableViewDataSource {

    var listTeams: NSArray!
    var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //导入外部资源文件,文件名为team.plist
        let plistPath = Bundle.main.path(forResource:"team",ofType:"plist")
        //获取属性列表文件中的全部数据
        self.listTeams = NSArray(contentsOfFile: plistPath!)
        
        /*
        实例化表视图对象.
        第一个参数是表视图的frame属性.由于需要覆盖整个界面,这里取值是根视图frame.
        第二个参数是表视图的样式.plain是普通表视图.grouped是分组表视图.
        */
        self.tableView = UITableView(frame: self.view.frame, style: .plain)
        
        //设置表视图委托对象为self
        self.tableView.delegate = self
        self.tableView.dataSource = self
        
        self.view.addSubview(self.tableView)
    }
    
    // ↓ 数据源协议 ↓
    
    //表视图创建是在试图控制器加载时完成的,表视图显示的时候会调用表视图数据源对象的此方法,询问当前节中的行数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.listTeams.count
    }
    
    //表视图单元格显示的时候会调用表视图数据源对象的此方法,为单元格提供显示数据.(每一行单元格都会调用一次)
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        //获取可重用单元格对象.
        var cell: UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: CellIndentifier)
        //上一行dequeueResuableCell(withIdentifier:)必须配合下面的判断使用.即先判断是否找到可以重用的单元格.如果没有,则通过单元格构造函数创建单元格对象.
        if(cell == nil){
            print("哈哈哈,cell是空呢")
            cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: CellIndentifier)
        }
        
        let row = (indexPath as NSIndexPath).row
        
        let rowDict = self.listTeams[row] as! NSDictionary
        cell.textLabel?.text = rowDict["name"] as? String
        
        let imagePath = String(format: "%@.png", rowDict["image"] as! String)
        cell.imageView?.image = UIImage(named: imagePath)
        
        cell.accessoryType = .disclosureIndicator //设置扩展视图
        return cell
    }


}
122666-ffd87ed8cecb939b.png
image.png

如果表视图控制器直接继承父类UITableViewController(class ViewController : UITableViewController {) , 那么不需要声明实现UITableViewDataSource和UITableViewDelegate协议(即上文class ViewController: UIViewController , UITableViewDelegate,UITableViewDataSource { ),其次也不需要手动把控制器类分配给表视图的委托属性delegate(self.tableView.delegate = self)和数据源属性DataSource(self.tableView.dataSource = self).因为UITableViewController已经实现了UITableViewDataSource和UITableViewDelegate协议,并且分配表视图的委托属性delegate和数据源属性dataSource.


直接继承UITableViewController类的代码实现:

import UIKit
let CellIndentifier = "CellIdentifier"

class ViewController: UITableViewController {
    
    var listTeams: NSArray!
    override func viewDidLoad() {
        super.viewDidLoad()
        //导入外部资源文件,文件名为team.plist
        let plistPath = Bundle.main.path(forResource:"team",ofType:"plist")
        //获取属性列表文件中的全部数据
        self.listTeams = NSArray(contentsOfFile: plistPath!)

        //这里不需要手动把控制器类分配给表视图的委托属性delegate和数据源属性DataSource.因为父类UITableViewController已经并且分配表视图的委托属性delegate和数据源属性dataSource.
//        self.tableView = UITableView(frame: self.view.frame, style: .plain)
//        //设置表视图委托对象为self
//        self.tableView.delegate = self
//        self.tableView.dataSource = self
//        self.view.addSubview(self.tableView)
        
    }
    
 
    //因为这是重写父类UITableViewController的方法,所以要加override关键字.
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.listTeams.count
    }
    
    //表视图单元格显示的时候会调用表视图数据源对象的此方法,为单元格提供显示数据.(每一行单元格都会调用一次)
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        //获取可重用单元格对象.
        var cell: UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: CellIndentifier)
        //上一行dequeueResuableCell(withIdentifier:)必须配合下面的判断使用.即先判断是否找到可以重用的单元格.如果没有,则通过单元格构造函数创建单元格对象.
        if(cell == nil){
            print("哈哈哈,cell是空呢")
            cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: CellIndentifier)
        }
        
        let row = (indexPath as NSIndexPath).row
        
        let rowDict = self.listTeams[row] as! NSDictionary
        cell.textLabel?.text = rowDict["name"] as? String
        
        let imagePath = String(format: "%@.png", rowDict["image"] as! String)
        cell.imageView?.image = UIImage(named: imagePath)
        
        cell.accessoryType = .disclosureIndicator //设置扩展视图
        return cell
    }
    
}

AppDelegate.swift代码func application部分需要替换:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        self.window = UIWindow(frame: UIScreen.main.bounds)
        self.window?.rootViewController = ViewController()
        self.window?.backgroundColor = UIColor.white
        self.window?.makeKeyAndVisible()
        
        return true
    }

猜你喜欢

转载自blog.csdn.net/weixin_34006468/article/details/87140267