0
顯示數據我的代碼:表視圖不會從JSON
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數據...只是在表中查看空白 和我嘗試另一個代碼,但結果相同(表視圖空白)... 我該怎麼辦?我不知道它的我的錯誤代碼或我的模擬器有問題,這樣的...
也許你應該對其進行調試。 – 2014-11-25 04:09:12
讓ypo設置tableview的Delegate&DataSource? – 2014-11-25 04:09:38
@Virussmca @Virussmca我試着設置UITableViewDelegate,UITableViewDataSource但結果相同 – Noob 2014-11-25 04:18:25