2014-11-04 38 views
1

在XCode 6.1中運行代碼時,ViewController中沒有任何東西出現。tableView不出現在ViewController中(swift)

import UIKit 

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 

    var tableView: UITableView! 
    var messages: [String] = [String]() 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     tableView = UITableView() 
     tableView.dataSource = self 
     tableView.delegate = self 
     self.view.addSubview(self.tableView) 

     //http://stackoverflow.com/questions/25413239/custom-uitablecellview-programmatically-using-swift 
     //Auto-set the UITableViewCells height (requires iOS8) 
     tableView.rowHeight = UITableViewAutomaticDimension 
     tableView.estimatedRowHeight = 44 

     // add something to messages 
     messages.append("foo") 
     messages.append("bar") 
    } 

    // TABLEVIEWS 
    //func numberOfSectionsInTableView(tableView: UITableView!) -> Int { 
    // return 1 
    //} 

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     var count = messages.count ?? 0 
     NSLog("message count: \(count)") 
     return count 
    } 

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     //var cell = tableView.dequeueReusableCellWithIdentifier("MyCell") as MyCell 
     var cell = UITableViewCell() 
     NSLog("row[\(indexPath.row)]: \(messages[indexPath.row])") 
     cell.textLabel.text = messages[indexPath.row] 
     return cell 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 
} 

回答

4

試試這個代碼:

override func viewDidLoad() { 
    super.viewDidLoad() 
    tableView = UITableView() 
    tableView.dataSource = self 
    tableView.delegate = self 
    self.view.addSubview(self.tableView) 

    //Auto-set the UITableViewCells height (requires iOS8) 
    tableView.rowHeight = UITableViewAutomaticDimension 
    tableView.estimatedRowHeight = 44 
    tableView.frame = CGRectMake(0, 0, 320, 568) 

    // add something to messages 
    messages.append("foo") 
    messages.append("bar") 
} 

編輯:嘗試此屏幕的尺寸都:

tableView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height) 
+0

這不適用於多種屏幕尺寸。 – AG1 2014-11-04 08:27:55

+0

我已經更新了答案。 – 2014-11-04 08:34:05

0

嗯,爲什麼要這麼辛苦爲你的自我。在故事板中,您可以添加一個TableViewController到項目中,或者添加一個tableview給你的viewcontroller,它可以直接使用。控制器類應該從UITableViewController繼承。

+0

故事板隱藏你太多。我喜歡能夠以編程方式控制我的視圖層次結構。 – AG1 2014-11-11 03:03:52

+0

究竟是什麼隱藏你需要在應用程序? – user1700737 2014-11-11 21:23:18

相關問題