IOS学习笔记-UITableView绑定数据实例

本文介绍如何使用Swift创建一个UITableView,包括定义model、填充数据、配置cell以及实现UITableViewDataSource协议的方法来展示数据。

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

首先创建model,新建一个文件存放model类

import UIKit

class testModel: NSObject {
    var Title:String
    init(title:String){
        self.Title = title
    }
}

在controller中的class外,声明一个变量

var list:[testModel] = []

为list增加数据

override func viewDidLoad() {
    super.viewDidLoad()
    list = [testModel(title:"蜻蜓"),
            testModel(title:"蝴蝶"),
            testModel(title:"燕子"),
            testModel(title:"麻雀"),
            testModel(title:"飞机"),
            testModel(title:"大炮")]
}

将table view右键拖入类中绑定命名为listTable

@IBOutlet weak var listTable: UITableView!

为table view cell 命名 todoCell

这里写图片描述

在cell中放置一个label,并设置tag属性

这里写图片描述

让controller类继承UITableViewDataSource协议,并实现协议:

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    return list.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    let cell = self.listTable.dequeueReusableCellWithIdentifier("todoCell")! as UITableViewCell
    let todo = list[indexPath.row] as testModel
    let label = cell.viewWithTag(110) as! UILabel
    label.text = todo.Title
    return cell
}

右击storyboard中右击table view拖拉至控制器,选择dataSource,运行后,可见效果

本是自己的学习笔记,可能写的比较粗俗,欢迎吐槽

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值