ios - Swift:ViewController 中的 TableView

标签 ios iphone swift xcode uitableview

我在 MainstoryBoard 中有一个 ViewController。我添加了 TableView

主 Storyboard:

enter image description here

此外,我在 ViewController 类之外有一个数组,我希望数组中的对象显示在 TableView 中。

我不知道该怎么做。我在 TableViewViewController 之间连接了委托(delegate)。

最佳答案

您在类声明下方添加一个新的 TableView 实例变量。

@IBOutlet weak var tableView: UITableView!

要符合 UITableViewDelegateUITableViewDataSource 协议(protocol),只需在类声明中的 UIViewController 之后添加以逗号分隔的它们

之后我们需要实现 tableView(_:numberOfRowsInSection:), tableView(_:cellForRowAtIndexPath:)tableView(_:didSelectRowAtIndexPath:) ViewController 类中的方法,暂时将它们留空

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    ...

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0 // your number of cells here
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // your cell coding 
        return UITableViewCell()
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        // cell selected code here
    }
}

正如@ErikP 在评论中提到的,您还需要 设置

self.tableView.delegate = self

self.tableView.dataSource = self

viewDidLoad 方法中。

(或者在 Storyboard 中效果也很好)。

关于ios - Swift:ViewController 中的 TableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31673607/

相关文章:

ios - SKPaymentTransaction : what is transactionDate exactly?

使用四元数的 iPhone GLGravity 示例

ios - 保存后作为成员的 Realm 对象为零

ios - 刷新 token AWS Cognito用户池,代码块甚至没有运行

ios - 如何在 StoryBoard 中连接 UI Popover ViewController

iphone - 如何从 iOS 应用程序使用 REST API 验证 Microsoft SharePoint 站点

ios - 部署 iPhone 配置文件

iphone - 可以在我的应用程序中将多个类的默认值注册到 NSUserDefaults 吗?

ios - NSUserDefaults 不保存整数

ios - CocoaPods 构建项目时出错