簡體   English   中英

tableView沒有出現在ViewController中(Swift)

[英]tableView not appearing in ViewController (swift)

在XCode 6.1中運行代碼時,ViewController中沒有任何內容。

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.
    }
}

嘗試以下代碼:

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)

嗯,為什么要對自己這么難。 在故事板上,您可以將TableViewController添加到項目中或將tableview添加到您的viewcontroller中,它將立即可用。 控制器類應繼承自UITableViewController。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM