Swift中UITableView的初步认识

本文介绍在Swift中使用UITableView的两种不同实现方式:一种是传统的类似于Objective-C的写法;另一种则是苹果官方推荐的更为优雅的方法,后者通过扩展来提高代码的可读性和组织性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.传统类似OC中的写法

//
//  ViewController.swift


import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

    override func loadView() {
        let tableView = UITableView()
        tableView.frame = UIScreen.mainScreen().bounds
        tableView.dataSource = self
        tableView.delegate = self

        view = tableView
    }

    // MARK: - 懒加载数据
    lazy var dataList:[String] = {
        return ["jack","zhangsan","xiaoming","lisi","lily"]
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    // MARK: - UITableViewDataSource
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataList.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // 1.创建cell
        var cell = tableView.dequeueReusableCellWithIdentifier("cell")
        if cell == nil{
            cell = UITableViewCell(style: UITableViewCellStyle.Default
                , reuseIdentifier: "cell")
        }

        // 2.设置数据
        cell?.textLabel?.text = dataList[indexPath.row]

        return cell!
    }
}

2.苹果官方推荐的更加优雅的写法

//
//  ViewController.swift

import UIKit

class ViewController: UIViewController {

    override func loadView() {
        let tableView = UITableView()
        tableView.frame = UIScreen.mainScreen().bounds
        tableView.dataSource = self
        tableView.delegate = self

        view = tableView
    }

    // MARK: - 懒加载数据
    lazy var dataList:[String] = {
        return ["jack","zhangsan","xiaoming","lisi","lily"]
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
    }

}

// 苹果官方建议,可以将数据代理方法单独写到一个扩展中,以便于代码的可读性
// extension 相当于OC的 category
extension ViewController:UITableViewDataSource,UITableViewDelegate{

    // MARK: - UITableViewDataSource
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataList.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // 1.创建cell
        var cell = tableView.dequeueReusableCellWithIdentifier("cell")
        if cell == nil{
            cell = UITableViewCell(style: UITableViewCellStyle.Default
                , reuseIdentifier: "cell")
        }

        // 2.设置数据
        cell?.textLabel?.text = dataList[indexPath.row]

        return cell!
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值