iOS項目開發實戰——學會使用TableView清單控制項(二)

來源:互聯網
上載者:User

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)注意:這一步大家很容易忘記,就是把當前的這個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 UIKitclass 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)實現效果如下:

 

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.