2016-06-29 2 views
4

Я пытаюсь построить uitableviewcontroller, и у меня возникают трудности с быстрым 3. Всякий раз, когда вызывается номерOfRowsInSection, он вызывается 4 раза, а затем приложение вылетает. Кто-нибудь знает, как реализовать это быстро 3?numberOfRowsInSection вызывает сбой в swift 3

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return 6; 

} 

В массиве есть 6 элементов, которые я хочу заполнить таблицей. Я распечатал подсчет массива для подтверждения. это контроллер полного обзора.

class PCRInpatientsViewController: UITableViewController 
{ 
var listInpatient = [PCRPatient](); 

override func viewWillAppear(_ animated: Bool) { 
    super.viewWillAppear(animated); 


    self.tableView.delegate = self; 
    self.tableView.dataSource = self; 
    self.tableView.separatorStyle = UITableViewCellSeparatorStyle.none; 

    self.title = "Inpatients"; 

    let view = self.view.frame; 
    let background = UIView(frame: view); 
    background.backgroundColor = Constants.medisasDarkGrey; 
    self.tableView.backgroundView = background; 

    self.definesPresentationContext = true; 

    getPatients(); 
    createUI(); 

} 

func getPatients() { 

    var array = [PCRPatient](); 
      let i = Patients.sharedInstance.patients 

      for int in 0..<i.count { 
       let d = i[int]; 

       if d.status == PCRPatientStatus.PreAdmit { 
        print(d.name) 
        array.append(d); 
       } 


      } 
    print(array.count); 
    self.listInpatient = array; 


} 

override func viewDidDisappear(_ animated: Bool) { 
    super.viewDidDisappear(animated); 

} 

func createUI(){ 


    self.navigationController?.navigationBar.barTintColor = Constants.medisasRed; 
    self.navigationController?.navigationBar.isTranslucent = false; 
    self.navigationController?.navigationBar.tintColor = UIColor.white(); 
    self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white()]; 


} 



override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return 6; 

} 

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
    return 150; 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> PCRCustomCell { 

    let patient = listInpatient[indexPath.row]; 
    print("sjddsodkso \(patient.name)"); 

    let cell = PCRCustomCell(reuse: "Inpatient", patient: patient); 
    cell.contentView.backgroundColor = Constants.medisasGrey; 


    return cell; 
} 

} 
+0

Я проверил и в массиве 6 элементов. Я добавил контроллер полного представления – PCR

+0

То, что он изначально был, но я изменил его на 6, потому что он рушился, и я хотел посмотреть, не сработает ли он, если бы я написал 6. Он все равно падает. Это бы хорошо работало в старом быстром, поэтому я считаю, что некоторые изменения с быстрым 3 являются причиной. – PCR

+0

Я полагаю, что я отнесусь к кому-то с большим знанием. Я с нетерпением жду, чтобы узнать, в чем проблема. –

ответ

2

Пара синтаксических изменений в Swift 3, которые необходимо включить. Xcode 8 beta часто предлагает правильные исправления для вашего кода, но не всегда. Я боролся с этим, прежде чем выяснять, что вы можете проверить обновленную документацию в бета-версии Xcode 8, нажав Shift + Command + 0 и поискать первые несколько символов почти любого. В этом случае найдите UITableViewDataSource, и вы увидите все, что я собираюсь отметить.

1) cellForRowAtIndexPath сейчас cellForRowAt. NSIndexPath сейчас IndexPath. Реализовать так:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    // if you use prototype cells 
    let cell = tableView.dequeueReusableCell(withIdentifier: "prototypeCellIdentifier") as! CustomUITableViewCell 

    // configure your cell 

    return cell 
} 

2) heightForRowAtIndexPath является так же в настоящее время heightForRowAt. Я не выполнил это лично, но, но из документации это реализовано так:

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 
    return float 
} 

3) Как уже отмечалось другие, numberOfRowsInSection должны быть динамичными, но я не верю, что это вызывает сбои.

Смежные вопросы