在Swift 2
中,处理将根据字典内容动态创建单元格的UITableView
。这本词典有38个条目。当我在“属性”检查器中手动将“表视图”部分设置为38行时,一切都按预期工作。
然而,这并不理想,我宁愿使用numberOfRowsInSection
来获取字典的数量,并以此方式创建行/单元格。当Att Inspector设置为1时,我得到一个越界错误。
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
这是我的代码:
import SwiftyJSON
import UIKit
class OurTableViewController2: UITableViewController {
@IBOutlet weak var menuButton: UIBarButtonItem!
var labels = [String: UILabel]()
var strings = [String]()
var objects = [[String: String]]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
//gets data that will be used for cells
let urlString = "http://handheldart.org/api/tags/"
if let url = NSURL(string: urlString) {
if let data = try? NSData(contentsOfURL: url, options: []) {
let json = JSON(data: data)
parseJSON(json)
}
}
//menu button at top left of screen
if self.revealViewController() != nil {
menuButton.target = self.revealViewController()
menuButton.action = "revealToggle:"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
}
//creates array 'objects'
func parseJSON(json: JSON) {
for result in json.arrayValue {
let id = result["id"].stringValue
let tagURL = result["url"].stringValue
let tagName = result["name"].stringValue
let obj = ["id": id, "tagURL": tagURL, "tagName": tagName]
//print (tagName)
objects.append(obj)
}
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
//create number of rows based on count of objects array
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print ("OBJECTS COUNT")
print (objects.count) //prints 38
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
let object = objects[indexPath.row]
cell.textLabel?.text = object["tagName"]!
return cell
}
有什么建议吗?