iOS项目开发实战——学会使用TableView列表控件(二)

这篇博客介绍了如何在Swift的iOS项目中使用TableView作为列表控件。通过新建Single View Controller,添加TableView,并实现UITableViewDataSource协议,详细阐述了设置Prototype Cells、Cell内的Label、数据绑定以及动态加载不同内容的方法。

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

       要在iOS开发中使用TableView列表控件,不仅可以直接使用TableViewController作为整个主界面,而且还可以使用TableView控件来实现。使用TableView可以进行更多的自定义,满足更多的需求。在开发中较为常用。具体实现如下:

(1)新建一个Single View Controller项目,语言选择Swift,然后在Main.storyboard中拖入一个TableView控件。此时看起来整个设计界面就和TableViewController创建的一样了。

然后在右侧的Prototype Cells中选择1,我们使用这个cell来进行设计。并在Cell中再拖入一个Label,设置这个Label的tag=101,当然这个tag值可以自己设置,在一个cell中的不同控件tag值不同就好了。

(2)把这个界面的Class值输入ViewController。

(3)在代码中ViewController实现一个Protocol,UITableViewDataSource,然后以下的2个方法必须要进行实现。

 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    
    
    
 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

(4)注意:这一步大家很容易忘记,就是把当前的这个TableView控件绑定到DataSource。这一步有两种方法:

1】绑定TableView控件到代码中,然后实现self.DataSource = self

2】简便方法,直接在storyboard中右击TableView,拖动到ViewController中,此时会出现dataSource,delegate.选中dataSource即可。


(5)设置刚才生成的Prototype Cells的ID,任意字符串都可,我设为cell。

(6)代码中实现如下:

  func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 3
  }

  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
    let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
    
    var title = cell.viewWithTag(101) as! UILabel
    title.text = "Hello ,Swift"
    
    return cell
    
  }

(7)运行程序,效果如下:


(8)但是有没有办法在cell中设置不同的文字呢,这是可以的,我只要声明一个数组,然后不同的cell就可以进行读取,实现代码如下:

import UIKit

class ViewController: UIViewController ,UITableViewDataSource{

  
  var array:[String] = ["Hello","iOS","Swift"]
  
  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    
  }


  func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 3
  }

  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
    let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
    
    var title = cell.viewWithTag(101) as! UILabel
    title.text = array[indexPath.row]
    
    return cell
    
  }


}

(9)实现效果如下:




github主页:https://github.com/chenyufeng1991  。欢迎大家访问!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值