ios - 使用 swift 创建 TableView

标签 ios swift

我一直在尝试使用 xcode 6 和 ios8 使用 swift 创建一个表格 View ,但我在模拟器上没有得到任何东西,只是显示空(白色)。

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var myArr = ["one","two","three","four","five"]

    @IBOutlet weak var table: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

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

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


    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")

        cell.textLabel?.text = self.myArr[indexPath.row]


        return cell;
    }

}

我什至尝试过拖动一些元素,如按钮、开关等,但我在模拟器上没有得到任何东西。如果我下载并运行任何代码,它就可以工作。

最佳答案

这是我的工作代码,我不明白前一个代码出了什么问题,但我创建了一个新项目,然后它就工作了。 我只是将 TableView 拖到 View Controller 并分配委托(delegate)和数据源 然后来到viewcontroller.swift并尝试

import UIKit

class ViewController: UIViewController {

    var items = ["a","b","c"]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

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


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

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


    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        var cell:UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "myCell") as UITableViewCell
        cell.textLabel?.text = self.items[indexPath.row]
        return cell
    }

}

关于ios - 使用 swift 创建 TableView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26341536/

相关文章:

ios - 是否可以隐藏 NFC 阅读 session 的 iOS 系统警报

ios - 使用 react-native 和 expo 为 iOS 应用程序设置不同的语言

ios - 在以编程方式实例化的 TableView Controller 中注册一个单元格

ios - 从服务器接收到数据后,如何在我的应用程序的 View Controller 标签中显示数据(从静态硬编码值更新)

ios - 更改约束后 UICollectionView 更新单元格大小

ios - 带有条件if语句的uialertview在ios中

ios - 将字典从 iOS 应用程序发送到 WatchKit - watchOS2

JSON 下载但没有添加到 UITable,但没有错误?

ios - 如何在 iOS 和 WatchKit 中更改图像 tintColor

ios - 设置以编程方式绘制的 View 的颜色