ios - 如何在 Swift 中点击表格 View 的单元格

标签 ios swift

这是我使用令人敬畏的 SWIFT 语言的第一天,我正在尝试用一些数据填充 TableView ,一切似乎都工作正常,但我想让我的 TableView 可单击并打印单击的项目的 ID但它似乎不起作用,我没有收到任何错误。

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var categories = [Category]()

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

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
    cell.textLabel?.text = categories[indexPath.row].Label



    return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
 println("You selected cell #\(indexPath.row)!")
}



override func viewDidLoad() {
    super.viewDidLoad()


    let reposURL = NSURL(string: "http://myserver.com/file.json")
    // 2
    if let JSONData = NSData(contentsOfURL: reposURL!) {
        // 3
        if let json = NSJSONSerialization.JSONObjectWithData(JSONData, options: nil, error: nil) as? NSDictionary {
            // 4
            if let reposArray = json["List"] as? [NSDictionary] {
                // 5
                for item in reposArray {
                    categories.append(Category(json: item))
                }
            }
        }
    }
}

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


}

最佳答案

您似乎忘记设置 UITableViewDelegate:

override func viewDidLoad() {
  super.viewDidLoad()
  self.tableView.delegate = self

}

如果您尚未在代码中将 tableView 定义为变量。您可以使用 Storyboard定义委托(delegate)和数据源。

storyboard

关于ios - 如何在 Swift 中点击表格 View 的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31810511/

相关文章:

swift - 我收到此错误 "Use of unresolved identifier ' countElement'”。我是 swift 的新手,所以我不知道出了什么问题

ios - React Native 中架构 x86_64 的 7 个重复符号

swift - 当用户来到 Controller 时如何存储开关值

swift - 将现代 Swift 语法更新为现代 Swift 语法,项目将不再编译

javascript - Xcode - UIWebview 不显示 CSS、Javascript 或外部内容

ios - 在 Swift 中获取 Cocoa Touch Framework 项目版本字符串

ios - 唯一标识符的图像缓存最佳实践

ios - SKMaps/Skobbler map 服务器宕机

ios - 如何在 xcode 7 中通过代码调用不同的 View

ios - 调度队列和 NSOperation 队列