Экран становится черным после перехода - PullRequest
7 голосов
/ 27 января 2020

Я попытался отладить это, но безрезультатно.

В основном, когда я переключаюсь с первого контроллера представления на второй контроллер представления, экран на мгновение становится черным. Код работает так, как я хочу, но экран становится черным для меня немного боли.

Вот код:

Результат с первой страницы:

func mapView(_ mapView: MGLMapView, tapOnCalloutFor annotation: MGLAnnotation) {
        self.performSegue(withIdentifier: "goToSecond", sender: self)
    }

контроллер второго вида:

override func viewDidLoad() {
    super.viewDidLoad()
    self.loadDataFromFirebase()
}

первая функция:

  func loadDataFromFirebase() {
           let db = Firestore.firestore()
           db.collection(restaurauntName).getDocuments { (snapshot, err) in
              if let err = err {
                 print("Error getting documents: \(err)")
                 return
              } else {
                 for document in snapshot!.documents {
                    let name = document.get("Name") as! String
                    let description = document.get("Description") as! String
                    self.names.append(name)
                    self.descriptions.append(description)
                 }
                 self.setupImages() //safe to do this here as the firebase data is valid
                 self.collectionView?.reloadData()
              }
           }
        }

эта функция настраивает макет страницы

func setupImages(){
        self.pages = [
            Page(imageName: self.imagesOne, headerText: names[0], bodyText: descriptions[0]),

            Page(imageName: self.imagesTwo, headerText: names[1], bodyText: descriptions[1]),

            Page(imageName: self.imagesThree, headerText: names[2], bodyText: descriptions[2]),

            Page(imageName: self.imagesFour, headerText: names[3], bodyText: descriptions[3]),

            Page(imageName: self.imagesFive, headerText: names[4], bodyText: descriptions[4]),
        ]

        self.collectionView?.backgroundColor = .white
        self.collectionView?.register(PageCell.self, forCellWithReuseIdentifier: "cellId")

        self.collectionView?.isPagingEnabled = true
    }

Это настраивает управление страницей

lazy var pageControl: UIPageControl = {
    let pc = UIPageControl()
    pc.currentPage = 0
    pc.numberOfPages = 5
    pc.currentPageIndicatorTintColor = .red
    pc.pageIndicatorTintColor = .gray
    return pc
}()

расширение контроллера смахивания:

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

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

        return pages.count

    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! PageCell

        let page = pages[indexPath.item]
        cell.page = page
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.frame.width, height: view.frame.height)
    }

Пожалуйста, дайте мне знать, если мне нужно добавить что-нибудь еще! любая помощь приветствуется

вот ролик проблемы на YouTube:

https://www.youtube.com/watch?v=vQGiw3Jd9pM

С тех пор я обнаружил, что когда я комментирую Метод Firebase проблема исчезает.

Ответы [ 2 ]

2 голосов
/ 11 февраля 2020

Я решил проблему! проблема была в том, в каком порядке вызывались функции.

Я не осознавал, что страница настраивалась слишком быстро для firebase, поэтому теперь я вызываю функцию раньше! в представлении появится

override func viewWillAppear(_ animated: Bool) {
        print("Done")
        super.viewWillAppear(animated)

        self.loadDataFromFirebase()
}

Спасибо всем, кто помог!

0 голосов
/ 11 февраля 2020

кажется, что ваш метод loadDataFromFirebase () занимает много времени для выполнения в главном потоке, вызывая его зависание. Переместите вашу выборку в фоновый поток и обновите ваш пользовательский интерфейс после того, как данные были получены в это время, покажите индикатор загрузки или что-то в этом роде. Попробуйте:

func loadDataFromFirebase() {
    DispatchQueue.global(qos: .userInitiated).async { [weak self] in 
        // Fetch and convert data
        let db = Firestore.firestore()
        ...
        DispatchQueue.main.async {
             // Update your UI components with the data here
             self.setupImages()
             self.collectionView?.reloadData()
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...