UICollectionView reloadData永远不会通过数据源

时间:2017-07-09 19:39:35

标签: ios swift uicollectionview reloaddata ios-multithreading

我正在尝试在UICollectionView中显示数据,其效果与我在整个应用程序中完全一样,但出于某种原因,它在这种情况下不起作用:

以下是了解问题所需的代码:

SomeController:

func showContactsView(sender: RoundButton) -> Void {
        DispatchQueue.main.async {
            self.someView = SomeView()
            self.view.addSubview(self.someView)
            self.someView.setSomeViewViewConstraints(container: 
    self.view)
            self.someView.alpha = 0.0
            self.someView.contactsCollectionView.delegate = self
            self.someView.contactsCollectionView.dataSource = self
            self.someView.tabControlCallbacks["contacts"] = self.searchContacts
        }
    }

控制器初始化包含UICollectionView的视图。这部分由autolayout和约束处理,我没有问题。 它还继承自UIColleCtionViewDelegate和UICollectionViewDataSource。 :

class SomeController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate

视图初始化collectionView并由SegmentedControl显示,它完美地运行:

private func initCollectionViews() {
        let layout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        layout.itemSize = CGSize(width: 50, height: 50)

        contactsCollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        contactsCollectionView.backgroundColor = UIColor.black.withAlphaComponent(0.6)
        contactsCollectionView.showsVerticalScrollIndicator = false
        contactsCollectionView.showsHorizontalScrollIndicator = false
        contactsCollectionView.register(AModelCollectionViewCell.self, forCellWithReuseIdentifier: "ContactsSelectModelCell")
        contactsCollectionView.translatesAutoresizingMaskIntoConstraints = false


        // Constraints to add when view is set dynamically
        contactsCollectionViewConstraints["leading"] = NSLayoutConstraint(item: contactsCollectionView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 0.0)
        contactsCollectionViewConstraints["trailing"] = NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: contactsCollectionView, attribute: .trailing, multiplier: 1.0, constant: 0.0)
        contactsCollectionViewConstraints["top"] = NSLayoutConstraint(item: tabControl, attribute: .bottom, relatedBy: .equal, toItem: contactsCollectionView, attribute: .top, multiplier: 1.0, constant: 0.0)
        contactsCollectionViewConstraints["bottom"] = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: contactsCollectionView, attribute: .bottom, multiplier: 1.0, constant: 0.0)
    }

并且分段控制值的显示值发生了变化:

func cleanViews() {
        if self.contactsCollectionView.superview != nil {
            self.contactsCollectionView.removeFromSuperview()
        }
        if self.favoritesCollectionView.superview != nil {
            self.favoritesCollectionView.removeFromSuperview()
        }
    }

func bounce() {
        self.cleanViews()
        switch self.actualControl {
        case -1:
            break
        case 0:
            // Some code
        case 1:
            self.addSubview(self.contactsCollectionView)
            for constraint in self.contactsCollectionViewConstraints {
                self.addConstraint(constraint.value)
            }
            if let callback = self.tabControlCallbacks["contacts"]! {
                callback()
            }
        default:
            fatalError("Unknown control")
        }
    }

    // Selectors UISegmentedControl
    func valueChanged(sender: UISegmentedControl) {
        if sender.selectedSegmentIndex == actualControl {
            tabControl.isMomentary = true
            sender.selectedSegmentIndex = -1
            tabControl.isMomentary = false
        }
        actualControl = sender.selectedSegmentIndex


        DispatchQueue.main.async {
            self.bounce()
        }
    }

正如您所看到的,我正在设置从控制器到视图的回调,以便对我的网络执行操作并获取数据以显示在collectionView上。以下是控制器中的方法:

  //Collection Views Actions/Callbacks for selectContactsView
    func searchContacts() -> Void {
        let params : [String:Any] = [
            "id" : "-1",
            "name_begin" : ""
        ]

        self.network?.get(......, callback: afterSearchContacts)
    }

    func afterSearchContacts() -> Void {

        DispatchQueue.main.async {

            self.contactsSearchResults.removeAll()
            let usersData : [[String:Any]] = self.network?.lastResponse!["users"] as! [[String:Any]]
            let groupsData : [[String:Any]] = self.network?.lastResponse!["groups"] as! [[String:Any]]

            for userData in usersData {
                self.contactsSearchResults.append(User(fromData: userData))
            }
            for groupData in groupsData {
                self.contactsSearchResults.append(Group(fromData: groupData))
            }
            self.contactsView.contactsCollectionView.reloadData()
        }
    }

reloadData无效。在解释哪个部分正在工作以及哪个部分不工作之前,以下是委托和数据源的方法:

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


        switch self.contactsView.actualControl {
        case 1:

            if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ContactsSelectModelCell", for: indexPath) as? AModelCollectionViewCell {
                cell.model = contactsSearchResults[indexPath.item]
                cell.fillCell()
                return cell
            }
        case 0:
                //some Code
                return cell
            }
        default:
            print("Unknown cell type")
        }
        fatalError("Unknown cell type")
    }

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

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let count = collectionView == contactsView.contactsCollectionView ? contactsSearchResults.count : favoritesSearchResults.count

        return count
    }

    //MARK: - UICollectionViewFlowLayoutDelegate
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 50.0, height: 50.0)
    }

我有一个自定义集合视图单元格,正在处理其他collectionViews,所以没有问题。当我进行注册时,我还会注意区分所有不同CollectionView的标识符。 在这种情况下,当我使用断点时,部分中的项目数是> 0但是当我在网络设置contactsSearchResult之后在主线程中执行reloadData时,它永远不会通过collectionView cellForItemAt。

有什么想法吗?

1 个答案:

答案 0 :(得分:-2)

对于那些阅读这篇文章的人来说,我最终编写了自己的CollectionView。像魅力一样工作。