2016-12-01 5 views
2

У меня есть UIViewController с UISegmentedControl, из которого я хотел бы представить UITableViewController как пирог, когда я нажимаю на segmentedControl сегменте. Проблема, с которой я сталкиваюсь, - это момент, когда я нажимаю на сегмент, popover начинает загружаться, но сбой при загрузке myPopoverTableViewController. Он падает ватрибуты UITableViewCell являются нулевыми, когда инстанцировании UITableView как пирог

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell, заявив, что атрибуты моего PopoverTableViewCell: nil.

Ради простоты я буду ссылаться на мои классы здесь:

myViewController: MyViewController 
myPopoverTVController: PopoverTableViewController 
myPopoverTVCell: PopoverTableViewCell 

В lldb, я проверил для значений клетки, dataSource, и кажется, что единственное, что ноль являются атрибуты из myPopoverTVCell, который я зарегистрироваться в myPopoverTVController's viewWillAppear с помощью следующей строки:

tableView.register(PopoverTableViewCell.self, forCellReuseIdentifier: "cell") 

myPopoverTVController не подключен через поповер Segue (хотя я пробовал) в myViewController. Я проверил, что у меня есть PopoverTableViewCell, указанный в классе для ячейки прототипа myPopoverTVController's. Я дважды проверил соединения из ячейки с классом PopoverTableViewCell. Я проверил, что у меня есть идентификатор ячейки таблицы, установленный на cell на раскадровке.

Вот как я начинаю поповер от myViewController после Apple's code:

@IBAction func segmentedControlAction(_ sender: UISegmentedControl) { 
    // instantiate the PopoverTableViewController 
    let popoverTVC = PopoverTableViewController() 
    // set variables on it 
    popoverTVC.selectedSegmentIndex = sender.selectedSegmentIndex 
    popoverTVC.currentRegion = currentRegion 
    // disignate presentation style as a popover 
    popoverTVC.modalPresentationStyle = .popover 

    present(popoverTVC, animated: true, completion: nil) 

    let presentationController = UIPopoverPresentationController(presentedViewController: popoverTVC, presenting: self) 
    presentationController.permittedArrowDirections = .up 
    presentationController.sourceView = view 
    presentationController.sourceRect = segmentedControl.frame 
} 

На myPopoverTVController, вот что мой cellForRowAt indexPath выглядит следующим образом:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    // let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! PopoverTableViewCell 
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! PopoverTableViewCell 

    // Configure the cell... 
    switch selectedSegmentIndex { 
    case 0, 1: 
     cell.areaLabel.text = popoverStringArray[indexPath.row] 

    case 2: 
     let countryList = locationManager.countryList 
     let countryCodes = locationManager.countryCodes 

     cell.areaLabel?.text = countryList[indexPath.row] 
     cell.flagLabel?.text = countryCodes[indexPath.row] 

    default: 
     break 
    } 

    return cell 
} 

Я проверил переменные, которые устанавливаются при конкретизации на myViewController, и у всех есть ценности. Это только атрибуты tableViewCell, которые являются nil. - lldb возвращает адрес памяти для ячейки при вводе po cell. Я установил UITableViews миллион раз, но я не могу понять эту штуку. Любые предложения re: то, что я делаю неправильно, очень ценится. Я буду уверена, что моя проблема - поразительное глупое упущение с моей стороны. Спасибо за чтение.

+0

У вас есть ячейки с идентификатором повторного использования «клеток» с классом PopoverTableViewCell? Проверяйте идентификатор повторного использования один раз. – Rajat

+0

Да, это была одна из первых вещей, которые я проверил. Я почти уверен, что это связано с созданием popover, поскольку я много раз настраивал TVC. – Adrian

+0

Попробуйте создать экземпляр объекта PopoverTableViewController, как этот «let controller = storyboard.instantiateViewController (withIdentifier:« someViewController ») как! PopoverTableViewController – Rajat

ответ

0

Я бросил полотенце, пытаясь использовать код Apple и разработал альтернативный метод, чтобы заставить popover работать.

I ctrl+dragged в раскадровке от моего myViewController до myPopoverTVController. Я установил идентификатор segue на popoverSegue и установил его для отображения в виде popover. Я также указал опорную точку.

Оттуда я внутренностей код в segmentedControlAction(), чтобы заменить его следующим:

@IBAction func segmentedControlAction(_ sender: UISegmentedControl) { 

    self.performSegue(withIdentifier: "popoverSegue", sender: segmentedControl.selectedSegmentIndex) 

} 

Я добавил следующий код к prepareForSegue на myViewController:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
    if segue.identifier == "popoverSegue" { 
     let destinationViewController = segue.destination as! PopoverTableViewController 
     destinationViewController.selectedSegmentIndex = sender as! Int 
     destinationViewController.currentRegion = currentRegion 


     let popoverController = destinationViewController.popoverPresentationController 

     if popoverController != nil { 
      popoverController?.delegate = self 
     } 
    } 
} 

Я также добавил делегат до myViewController с расширением:

extension MyViewController: UIPopoverPresentationControllerDelegate { 
    func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { 
     return .none 
    } 
} 

Наконец, я вынул локальную ссылку на источник данных в myPopoverTVController так теперь выглядит следующим образом:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! PopoverTableViewCell 

    // Configure the cell... 
    switch selectedSegmentIndex { 
    case 0: 
     cell.areaLabel.text = locationManager.cityList(geographicRegion: currentRegion!)[indexPath.row] 
     cell.flagLabel.isHidden = true 

    case 1: 
     cell.areaLabel.text = locationManager.stateList(geographicRegion: currentRegion!)[indexPath.row] 
     cell.flagLabel.isHidden = true 

    case 2: 
     cell.areaLabel?.text = locationManager.countryList[indexPath.row] 
     cell.flagLabel?.text = locationManager.countryCodes[indexPath.row].flag() 

    default: 
     break 
    } 

    return cell 
} 

... и это сработало.

Конец;)