我的代码:
import UIKit
class HomeVCHome: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
var names: [String] = []
var contacts: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self;
self.tableView.dataSource = self;
let url=NSURL(string:"http://mysite/json.aspx")!
let allContactsData=NSData(contentsOfURL:url)
var allContacts: AnyObject! = NSJSONSerialization.JSONObjectWithData(allContactsData!, options: NSJSONReadingOptions(0), error: nil)
if let json = allContacts as? Array<AnyObject> {
print(json)
for index in 0...json.count-1 {
let contact : AnyObject? = json[index]
print(contact)
let collection = contact! as Dictionary<String, AnyObject>
print(collection)
print(collection["name"])
let name : AnyObject? = collection["name"]
let cont : AnyObject? = collection["cont"]
names.append(name as String)
contacts.append(cont as String)
}
}
println(names)
println(contacts)
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return self.names.count;
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
println("You selected name : "+names[indexPath.row])
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
var cell = tableView.dequeueReusableCellWithIdentifier("cell") as? UITableViewCell
println("ok 1")
if !(cell != nil) {
cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "cell")
}
println("ok 2")
cell?.textLabel.text=self.names[indexPath.row]
cell?.detailTextLabel?.text = self.contacts[indexPath.row]
println("ok 3")
return cell!
}
}
我尝试运行,我无法在tableView中看到我的数据...在表格视图中只是空白 我尝试另一个代码,但相同的结果(表视图空白)... 我该怎么办?我不知道我的错误代码或我的模拟器有这样的问题...
答案 0 :(得分:2)
请更改方法并尝试:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier) as UITableViewCell
cell.textLabel.text=self.names[indexPath.row]
cell.detailTextLabel?.text = self.contacts[indexPath.row]
return cell
}