iOS开发④表视图

概述

表视图组成

表视图是iOS开发中最重要的视图,它以列表的形式展示数据。表视图又一下部分组成:

  • 表头视图:表视图最上边的视图

  • 表脚视图:表视图最下边的视图

  • 单元格(cell):表视图中每一行的视图

  • 节(section):由多个单元格组成,应用于分组列表

    • 节头

    • 节脚

表视图的相关类

UITableView继承自UIScrollView,且有两个协议:UITableViewDelegate和UITableViewDataSource。此外UITableViewCell类时单元格类,UITableViewController类时UITableView的控制器,UITableViewHeaderFooterView用于为节头和节脚提供视图。

《iOS开发④表视图》

表视图分类

  • 普通表视图:主要用于动态表,而动态表一般在单元格数目未知的情况下使用

  • 分组表视图:一般用于静态表,用来进行界面布局

单元格的组成和样式

单元格由图标、主标题、副标题、扩展视图组成,可以根据需要进行选择,其中内置的扩展视图在枚举类型UITableViewCellAccessoryType中定义:

Swift枚举成员Objective-C枚举成员说明
noneITableViewCellAccessoryNone没有扩展图标
disclosureIndicatorUITableViewCellAccessoryDisclosureIndicator扩展指示器,为箭头+问号
detailDisclosureButtonUITableViewCellAccessoryDetailDisclosureButton细节展示图,为问号
checkmarkUITableViewCellAccessoryCheckmark选中标志,图标为勾
detailButtonUITableViewCellAccessoryDetailButton细节详情展示,图标为问号

内置的单元格样式在枚举类型UITableViewCellStyle中定义:

Swift枚举成员Objective-C枚举成员说明
defaultUITableViewCellStyleDefault默认样式
subtitleUITableViewCellStyleSubtitle有图标、主标题、副标题、副标题在主标题的下面
value1UITableViewCellStyleValue1有主标题、副标题,主标题左对齐、副标题右对齐,可以有图标
2alue3UITableViewCellStyleValue2有主标题、副标题,主标题和副标题居中对齐,无图标

数据源协议与委托协议

UITableViewDataSource

数据源协议主要为表视图提供数据,主要方法如下

方法返回类型说明
func tableView(UITableView, cellForRowAt: IndexPath)UITableViewCell为表视图单元格提供数据,必须实现
tableView(UITableView, numberOfRowsInSection: Int)Int返回某个节中的行数,必须实现
tableView(UITableView, titleForHeaderInSection: Int)String返回节头的标题
tableView(UITableView, titleForFooterInSection: Int)String返回节脚的标题
numberOfSections(in: UITableView)Int返回节的个数
sectionIndexTitles(for: UITableView)[String]?返回表示图节索引标题

UITableViewDelegate

委托协议主要主要用来设定表视图中节头和节脚的标题,以及一些动作事件,主要方法如下

方法返回类型说明
tableView(UITableView, didSelectRowAt: IndexPath)单元格响应事件
tableView(UITableView, accessoryButtonTappedForRowWith: IndexPath)扩展视图响应事件

简单表视图

UIViewController根视图控制器实现表视图

步骤

  1. 创建一个iOS工程

  2. 从对象库中拖入一个TableView到storyboard文件中,并将TableView覆盖整个View

  3. 打开Table View的属性检查器,将PrototypeCells的值设为1,注意不要添加多个,否则会发生错误;此时Table View会添加一个Table View Cell。

  4. 打开Table View Cell的属性检查器,设置Identifier属性。

  5. 注册UITableViewDataSource和UITableViewDelegate协议

  6. 编写代码实现功能

实现

//
//  ViewController.swift
//  TableViewDemo
//
//  Created by Michael on 2016/10/26.
//  Copyright © 2016年 Michael. All rights reserved.
//

import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
    
    //全部数据
    var listItems: NSArray!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //读取资源文件数据
        let listPath = Bundle.main.path(forResource: "team", ofType: "plist")
        self.listItems = NSArray(contentsOfFile: listPath!)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    //返回列表每行的视图
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    //根据Identifier找到Cell
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomId", for: indexPath)
        let row = indexPath.row
        
        let rowDict = self.listItems[row] as! NSDictionary
        cell.textLabel?.text = rowDict["name"] as? String
        cell.detailTextLabel?.text = "123"
        
        let imagePath = String(format: "%@.png", rowDict["image"] as! String)
        cell.imageView?.image = UIImage(named: imagePath)
        cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
        return cell
    }

    //返回条目数目
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.listItems.count
    }
    
    //响应条目点击事件
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("点击事件")
    }
    
}

示例图

  • none模式

《iOS开发④表视图》

  • disclosureIndicator

《iOS开发④表视图》

UITableViewController根视图控制器实现表视图

步骤

  1. 创建一个iOS工程

  2. 删除storyboard中View Controller Scene 中的View Controller,再从对象库拖入一个Table View Controller到设计界面

  3. 打开Table View Controller属性检查器,勾选Is Initial View Controller选项,否则应用启动后是黑屏

  4. 将ViewController类的父类由UIViewController改为UITableViewController

  5. 打开View Controller的属性选择器在Class列表中选择ViewController

  6. UITableViewController默认以注册UITableViewDataSource和UITableViewDelegate协议,不需要再注册

实现

import UIKit

class ViewController: UITableViewController {
    
    //全部数据
    var listItems: NSArray!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //读取资源文件数据
        let listPath = Bundle.main.path(forResource: "team", ofType: "plist")
        self.listItems = NSArray(contentsOfFile: listPath!)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    //返回列表每行的视图
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomId", for: indexPath)
        let row = indexPath.row
        
        let rowDict = self.listItems[row] as! NSDictionary
        cell.textLabel?.text = rowDict["name"] as? String
        cell.detailTextLabel?.text = "123"
        
        let imagePath = String(format: "%@.png", rowDict["image"] as! String)
        cell.imageView?.image = UIImage(named: imagePath)
        cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
        return cell
    }

    //返回条目数目
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.listItems.count
    }
    
    //响应条目点击事件
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("点击事件")
    }
    
}

示例图

  • detailButton模式

《iOS开发④表视图》

  • checkmark模式

《iOS开发④表视图》

自定义单元格

步骤

  1. 创建一个表视图工程

  2. 修改根视图控制器为表视图控制器UITableViewController,参照上节的步骤

  3. 从对象库中拖入控件到单元格内部,比如Lable和ImageView

  4. 创建自定义单元格类CustomCell文件,并继承UITableViewCell类

  5. 在设计界面中选择View Controller Scene中的Table View Cell,并打开属性检查器,将Class设为CustomCell类,并设置单元格的Identifier

  6. 为单元格中的控件Label和ImageView控件连接输出接口,将控件绑定到CustomCell类中

  7. 打开ViewController类,编写代码实现

实现

  • CustomCell类

//
//  CustomCell.swift
//  CustomCell
//
//  Created by Michael on 2016/10/25.
//  Copyright © 2016年 Michael. All rights reserved.
//

import UIKit

class CustomCell: UITableViewCell {

    @IBOutlet weak var mImage: UIImageView!
    @IBOutlet weak var mLabel: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}
  • ViewController类

//
//  ViewController.swift
//  SimpleTableView
//
//  Created by Michael on 2016/10/24.
//  Copyright © 2016年 Michael. All rights reserved.
//

import UIKit

class ViewController: UITableViewController {
    
    var listItems: NSArray!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let listPath = Bundle.main.path(forResource: "team", ofType: "plist")
        self.listItems = NSArray(contentsOfFile: listPath!)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.listItems.count
    }
    
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    //找到自定义单元格
        let cell:CustomCell! = tableView.dequeueReusableCell(withIdentifier: "CustomCellId", for: indexPath) as? CustomCell
        //let cell = UITableViewCell(style: .value1, reuseIdentifier: "CellIdentifier")
        let row = indexPath.row
        
        let rowDict = self.listItems[row] as! NSDictionary
        //设置控件属性
        cell.mLabel.text = rowDict["name"] as? String
        
        let imagePath = String(format: "%@.png", rowDict["image"] as! String)
        cell.mImage.image = UIImage(named: imagePath)
        cell.accessoryType = .disclosureIndicator
        return cell
        
    }
}

示例图

《iOS开发④表视图》

    原文作者:刘涤生
    原文地址: https://segmentfault.com/a/1190000007320614
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞