似乎有十几种不同的方法可以做到这一点。这是我带来的最精简,但我得到了空白细胞。很近!
接下来我的圣杯是将这一切全部放入自定义单元格,这是我的第一步。
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var names = []
@IBOutlet var myTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string:"http://MYURL-here-which-pulls-down-the-JSON.json")
let JSONData = NSData(contentsOfURL: url)
var err: NSError?
let JSONResult = NSJSONSerialization.JSONObjectWithData(JSONData, options: nil, error: nil) as NSArray
var _names: NSMutableArray = NSMutableArray()
for item: AnyObject in JSONResult {
let name: NSString = item["name"] as NSString
_names.addObject(name)
}
self.names = _names
println(self.names)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return names.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
// THIS LINE IS THE ONE ***************************************************
// NO VALUE TO DISPLAY ****************************************************
cell.textLabel?.text = names[indexPath.row]
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
答案 0 :(得分:1)
问题在于您自己创建了单元格。你不应该这样做。
在表视图中使用Interface Builder中的重用标识符创建一个单元格,并将单元格样式设置为Basic
。然后你可以使用这样的代码:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier",
indexPath: indexPath) as UITableViewCell
cell.textLabel?.text = names[indexPath.row]
return cell
}