Xcode9学习笔记42

来源:互联网 发布:交通银行软件开发待遇 编辑:程序博客网 时间:2024/05/17 07:56

import UIKitclass ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {//表格视图数据源协议、表格视图代理协议    override func viewDidLoad() {        super.viewDidLoad()        // Do any additional setup after loading the view, typically from a nib.        let rect = CGRect(x: 0, y: 40, width: 320, height: 420)//创建一个显示区域        let tableView = UITableView(frame: rect)//初始化一个表格视图,并设置其位置和尺寸        tableView.delegate = self//设置表格视图的代理为当前的视图控制器类        tableView.dataSource = self//设置表格视图的数据源为当前的视图控制器类        self.view.addSubview(tableView)//将表格视图添加到当前视图控制器的根视图中    }        //添加一个代理方法,用来设置表格视图拥有5行单元格    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {        return 5    }        //添加一个代理方法,用来初始化或复用表格视图中的单元格    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {        let identifier = "reusedCell"//创建一个字符串,作为单元格的复用标识符        //单元格的标识符可以看作是一种复用机制,此方法可以从所有已经开辟内存的单元格里面,选择一个具有同样标识符的、空闲的单元格        var cell = tableView.dequeueReusableCell(withIdentifier: identifier)        //如果在可重用单元格队列中,没有可以重复使用的单元格,则创建新的单元格。新单元格拥有一个复用标识符        if cell == nil {            cell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: identifier)        }        cell?.textLabel?.text = "Cell Title here."//默认样式的单元格拥有一个标签对象,设置其文字内容        cell?.detailTextLabel?.text = "Detail information here."//标签下方有个字体较小的文字描述        let img1 = UIImage(named: "1")//读取图片素材        let img2 = UIImage(named: "2")        cell?.imageView?.image = img1//设置单元格默认图标        cell?.imageView?.highlightedImage = img2//设置单元格高亮图标                return cell!    }    override func didReceiveMemoryWarning() {        super.didReceiveMemoryWarning()        // Dispose of any resources that can be recreated.    }}



原创粉丝点击