2016-09-07 6 views
1

Swift 2에서 UITableView에 작업하면 사전의 내용을 기반으로 셀이 동적으로 생성됩니다. 사전에는 38 개의 항목이 있습니다. Attributes Inspector에서 테이블 뷰 섹션을 수동으로 38 행으로 설정하면 모든 것이 예상대로 작동합니다.numberOfRowsInSection이 속성 검사기를 덮어 쓰지 않음

그러나 이것은 이상적인 것이 아니며, numberOfRowsInSection을 사용하여 사전을 계산하고 행/셀을 이렇게 만들 수 있습니다. Att Inspector가 1로 설정되면 범위 초과 오류가 발생합니다.

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 
    } 

어떤 제안 : 여기

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]' 

내 코드?

+0

을 당신은 왜 당신이 행 수를 설정하려고 UITableViewDelegate 및 UITableViewDataSource – WMios

+0

에 부합되지 않는다 - 당신은있는 tableview 검사기 속성에서 그렇게 할 수 있습니다. 귀하의 데이터가 모두 동적 인 경우 귀하의 스토리 보드에 있습니까? – Wain

+0

원래 디자인을 테스트하기 위해 그곳에 셀을 만들었습니다. & 스토리 보드에서 소급하여 움직이고 있습니다. 간단히 말해서 TableView를 동적으로 설정하는 것을 잊어 버렸습니다! – pruette

답변

1

당신이 tableview의 content 속성을 "Static Cells"로 표시했기 때문입니다. tableview의 내용을 "Dynamic Prototypes"로 설정해야합니다. > 내용 ""첫 번째 특성에 동적 프로토 타입 "을 선택

enter image description here