使用Swift在TableView中显示数组项

6

使用Swift编程语言时,我无法在表格视图中显示数组元素。我做了一些研究,但无法解决这个问题。下面是我的代码,并可以从这里下载项目的.zip文件:http://1drv.ms/1Ca2hyp

我也可以提供一些视频,总共11分10秒。

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var myTableView: UITableView!
    var cars = [String]()
    var newCar: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        cars = ["BMW","Audi", "Volkswagen"]
    }

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

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

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cars.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell

        cell.textLabel?.text = cars[indexPath.row]

        return cell
    }

}

当你运行你的应用程序时会发生什么?你是否收到错误消息,还是屏幕上什么也看不到?你确定在Storyboard或xib文件中为单元格设置了单元格标识符为"myCell"吗? - Alexander
@Alexander 在Storyboard上的表格单元格与“myCell”具有相同的标识符。当我运行代码时,它没有报错。 - t1w
3个回答

8
您忘记将控制器注册为UITableView的数据源。
请在您的代码中添加以下内容:
@IBOutlet var myTableView: UITableView! {
    didSet {
        myTableView.dataSource = self
    }
}

3
    class SelectCategoryViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
        var CategeryArray = ["Food","Travel","Lifestyle","Card","MyReserve","Game","Songs","Movies","Entertainment","Business","Education","Finance","Drink","Sports","Social","Shopping"]



    override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.
            self.tableView.dataSource = self
            self.tableView.delegate = self
        }
}
    extension SelectCategoryViewController: UITableViewDelegate,UITableViewDataSource {

        func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return CategeryArray.count
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell")!
            cell.textLabel?.text = self.CategeryArray[indexPath.row]
            return cell
        }
    }

在Main.storyboard中设置标识符为TableViewCell,并为TableViewCell设置类名。

2
也许您忘记在视图控制器的viewDidLoad方法中添加这两行代码:
yourTableView.delegate = self

yourTableView.dataSource = self

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接