Я пытаюсь добавить раздел заголовка на страницу моего профиля с помощью swift (Xcode) без использования раскадровки - PullRequest
1 голос
/ 29 мая 2020

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

Завершение работы приложения из-за неперехваченного исключения 'NSInternalInconsistencyException', причина: 'не удалось удалить из очереди вид вида: UICollectionElementKindSectionFooter с идентификатором ProfileHeader - необходимо зарегистрировать перо или класс для идентификатора или подключить ячейку прототипа в раскадровке '

как мне это исправить?

private let reuseIdentifier = "Cell"
private let headerIdentifier = "ProfileHeader"

class UserProfileVC: UICollectionViewController, UICollectionViewDelegateFlowLayout {

// MARK: Properties
var USER_NAME: String = "Username"

override func viewDidLoad() {
    super.viewDidLoad()
    collectionView.register(UINib(nibName: headerIdentifier, bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)
    self.navigationItem.title = "Profile"

    self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    self.collectionView!.register(ProfileHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headerIdentifier)
    fetchUsersData()

}

// MARK: UICollectionViewDataSource

override func numberOfSections(in collectionView: UICollectionView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}


override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of items
    return 0
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {

    return CGSize(width: view.frame.width, height: 200)
}


override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

    //Declare header
    let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerIdentifier, for: indexPath) as! ProfileHeader
    return header
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)

    // Configure the cell

    return cell
}


// MARK - API

func fetchUsersData() {

    guard let currentUser = Auth.auth().currentUser?.uid else { return }
    print("Current user id is \(currentUser)")


    Database.database().reference().child("Users").child(currentUser).child(USER_NAME).observeSingleEvent(of: .value) { (snapshot) in
        guard let username = snapshot.value as? String else {return}
        self.navigationItem.title = username
    }
}
}

1 Ответ

1 голос
/ 29 мая 2020

ViewForSupplementary вызывается как для верхнего, так и для нижнего колонтитула

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerIdentifier, for: indexPath) as! ProfileHeader
            return header
        }
        else {
            fatalError("Unexpected element kind")
        }
    }

И если вы не хотите, чтобы viewForSupplementaryElement вызывался для набора нижнего колонтитула

extension UserProfileVC: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView,
                          layout collectionViewLayout: UICollectionViewLayout,
                          referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize.zero
    }
}

Также, пожалуйста remove

collectionView.register(UINib(nibName: headerIdentifier, bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)

Это регистрация ProfileHeader в качестве ячейки, а в следующем операторе вы также регистрируете ProfileHeader в качестве заголовка раздела self.collectionView!.register(ProfileHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headerIdentifier)

EDIT 2:

Поскольку OP сталкивается с трудностями в понимании интересного решения, я пишу весь класс ниже

private let reuseIdentifier = "Cell"
private let headerIdentifier = "ProfileHeader"

class UserProfileVC: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    // MARK: Properties
    var USER_NAME: String = "Username"

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.register(UINib(nibName: headerIdentifier, bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)
        self.navigationItem.title = "Profile"

        self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        self.collectionView!.register(ProfileHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headerIdentifier)
        fetchUsersData()

    }

    // MARK: UICollectionViewDataSource

    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }


    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {

        return CGSize.zero
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: view.frame.width, height: 200)
    }


    override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

        if kind == UICollectionView.elementKindSectionHeader {
            let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerIdentifier, for: indexPath) as! ProfileHeader
            return header
        }
        else {
            fatalError("Unexpected element kind")
        }
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)

        // Configure the cell

        return cell
    }


    // MARK - API

    func fetchUsersData() {

        guard let currentUser = Auth.auth().currentUser?.uid else { return }
        print("Current user id is \(currentUser)")


        Database.database().reference().child("Users").child(currentUser).child(USER_NAME).observeSingleEvent(of: .value) { (snapshot) in
            guard let username = snapshot.value as? String else {return}
            self.navigationItem.title = username
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...