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

       要在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)注意:这一步大家非常easy忘记,就是把当前的这个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  。欢迎大家訪问!


原文地址:https://www.cnblogs.com/yjbjingcha/p/6957003.html