Я пытаюсь установить 3 UICollectionView в одном UIViewController, и я создаю 3 разных выхода, как вы видите:

class myViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

    @IBOutlet weak var myCollectionView1: UICollectionView!
    @IBOutlet weak var myCollectionView2: UICollectionView!
    @IBOutlet weak var myCollectionView3: UICollectionView!

И для каждого из них

override func viewDidLoad() {
    super.viewDidLoad()

    self.myCollectionView1.delegate = self
    self.myCollectionView1.dataSource = self

    self.myCollectionView2.delegate = self
    self.myCollectionView2.dataSource = self

    self.myCollectionView3.delegate = self
    self.myCollectionView3.dataSource = self

}

А для протокола UICollectionView DataSource - для раздела

func numberOfSections(in collectionView: UICollectionView) -> Int {

    if (collectionView == self.myCollectionView1) {

        return 0

    } else if (collectionView == self.myCollectionView2) {

        return 0

    } else if (collectionView == self.myCollectionView3) {

        return 0

    }

    return 0

}

Для numberOfItemsInSection

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    if (collectionView == self.myCollectionView1) {

        return self.allName.count

    } else if (collectionView == self.myCollectionView2) {

        return self.pharmacyName.count

    } else if (collectionView == self.myCollectionView3) {

        return self.clinicName.count

    }

    return 0

}

И для cellAtIndexPath

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if (collectionView == myCollectionView1) {

        let cell1: allBrandCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell1", for: indexPath) as! allBrandCollectionViewCell

        cell1.name.text = allName[indexPath.row]
        cell1.phoneNumber.text = allPhoneNumber[indexPath.row]

        return cell1

    } else if (collectionView == myCollectionView2) {

        let cell2: pharmacyCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell2", for: indexPath) as! pharmacyCollectionViewCell

        cell2.name.text = pharmacyName[indexPath.row]
        cell2.phoneNumber.text = pharmacyPhoneNumber[indexPath.row]

        return cell2


    } else if (collectionView == myCollectionView3) {

        let cell3: clinicCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell3", for: indexPath) as! clinicCollectionViewCell

        cell3.name.text = clinicName[indexPath.row]
        cell3.phoneNumber.text = clinicPhoneNumber[indexPath.row]

        return cell3

    }

}

Так что проблема прямо сейчас, когда я пытаюсь создать проект, они показывают мне ошибку в cellForRowAtIndexPath:

Отсутствует возврат в функции, которая должна вернуть "UICollectionViewCell"

enter image description here

1
abdullaziz aman 5 Сен 2016 в 13:17

4 ответа

Лучший ответ
  • «cellForItemAt» имеет необязательный возвращаемый тип UICollectionViewCell. Но ваш код не возвращает ячейку, если ни одно из условий не соответствует.
  • Вы можете вернуть пустой объект UICollectionViewCell, если ни одно из условий не соответствует.

Исправленный код ниже:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if (collectionView == myCollectionView1) {

        let cell1: allBrandCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell1", for: indexPath) as! allBrandCollectionViewCell

        cell1.name.text = allName[indexPath.row]
        cell1.phoneNumber.text = allPhoneNumber[indexPath.row]

        return cell1

    } else if (collectionView == myCollectionView2) {

        let cell2: pharmacyCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell2", for: indexPath) as! pharmacyCollectionViewCell

        cell2.name.text = pharmacyName[indexPath.row]
        cell2.phoneNumber.text = pharmacyPhoneNumber[indexPath.row]

        return cell2


    } else if (collectionView == myCollectionView3) {

        let cell3: clinicCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell3", for: indexPath) as! clinicCollectionViewCell

        cell3.name.text = clinicName[indexPath.row]
        cell3.phoneNumber.text = clinicPhoneNumber[indexPath.row]

        return cell3

    }
   return UICollectionViewCell()
}
0
firstinq 5 Сен 2016 в 10:36

Вы должны вернуть ячейку во всех случаях , и вы просто не уловили каждую возможную ситуацию. [Что делать, если ячейка в методе cellForItemAt не будет соответствовать myCollectvion1-3?]

Итак, ваше решение может быть выполнено двумя способами:

1) поместите эту строку в конец метода cellForRow:

... 

return UITableViewCell() // like you have done in other method using `return 0`

ИЛИ

2) сделать еще {}

  ...       

    return self.clinicName.count

  } else {
      return UITableViewCell() // or any cell you want to create    
  }    
0
pedrouan 5 Сен 2016 в 10:48

Вам следует добавить еще одну последнюю строку, например return nil или которая возвращает tableview cell object, потому что, если каждый ваш оператор if не выполняется, функция должна что-то возвращать.

Во-вторых, в вашем операторе if в функции cellfor.. вы должны использовать self.myCollectionView1 не только myCollectionView1 в каждом операторе if, поэтому исправляйте его !!

0
Ketan Parmar 5 Сен 2016 в 10:22

Вам нужен оператор else, который должен возвращать UICollectionViewCell ().

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if (collectionView == myCollectionView1) {

        let cell1: allBrandCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell1", for: indexPath) as! allBrandCollectionViewCell

        cell1.name.text = allName[indexPath.row]
        cell1.phoneNumber.text = allPhoneNumber[indexPath.row]

        return cell1

    } else if (collectionView == myCollectionView2) {

        let cell2: pharmacyCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell2", for: indexPath) as! pharmacyCollectionViewCell

        cell2.name.text = pharmacyName[indexPath.row]
        cell2.phoneNumber.text = pharmacyPhoneNumber[indexPath.row]

        return cell2


    } else if (collectionView == myCollectionView3) {

        let cell3: clinicCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell3", for: indexPath) as! clinicCollectionViewCell

        cell3.name.text = clinicName[indexPath.row]
        cell3.phoneNumber.text = clinicPhoneNumber[indexPath.row]

        return cell3

    }
    else{

        return UICollectionViewCell() // any cell you must need to retrun. You can return nil if you want.
    }
}

Надеюсь, это поможет.

1
Riajur Rahman 5 Сен 2016 в 10:35