Выберите первый элемент в CollectionView Swift4

Я пытаюсь выбрать первый элемент в CollectionView, когда загружается Collectionview. Я нашел много решений для Swift 3, но ничего из этого не помогло мне в Swift4. Что я пробовал (viewDidAppear):

import UIKit
import SDWebImage

class PostsTab_Details: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

@IBOutlet weak var PostsSelectRarityCollectionView: UICollectionView!
@IBOutlet weak var RarityTypeLbl: UILabel!

//Center my Collectionview Horizontal
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {

        let totalCellWidth = 100 * (selectedPosts?.rarity.count)!
        let totalSpacingWidth = 10 * (3 - 1)

        let leftInset = (PostsSelectRarityCollectionView.frame.width - CGFloat(totalCellWidth + totalSpacingWidth)) / 2
        let rightInset = leftInset

        return UIEdgeInsetsMake(0, leftInset, 0, rightInset)

}

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

    return (selectedPosts?.rarity.count)!
}

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

    cell.PostssTab_DetailCollectionImage.sd_setImage(with: URL(string: (selectedPosts?.PostsImageURL)!))



    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    RarityTypeLbl.text = selectedPosts?.rarity[indexPath.row].rarity

}

 //Tried this also with IndexPath(item: 0, section: 0)
override func viewDidAppear(_ animated: Bool) {
    let selectedIndexPath = IndexPath(row: 0, section: 0)
    PostsSelectRarityCollectionView.selectItem(at: selectedIndexPath, animated: true, scrollPosition: .right)
}



var selectedPosts: Posts?

override func viewDidLoad() {
    PostsSelectRarityCollectionView.delegate = self
    PostsSelectRarityCollectionView.dataSource = self
}
}

Но это не работает... Надеюсь, кто-то знает, что я делаю не так..

заранее спасибо

Обновление: это сработало для меня сейчас, благодаря ответу Разиба:

override func viewWillAppear(_ animated: Bool) {
    self.collectionView(PostsSelectRarityCollectionView, didSelectItemAt: IndexPath(row: 0, section: 0))
}

1 ответ

Решение

Твой код мне подходит. Если вы хотите вызвать метод didSelectItemAt, используйте следующий код.

 override func viewDidAppear(_ animated: Bool) {
    self.PostsSelectRarityCollectionView(self.PostsSelectRarityCollectionView, didSelectItemAt: IndexPath(row: 0, section: 0))
}

Чтобы программно выбрать первый элемент в CollectionViewCell при загрузке Collectionview, вы должны написать код в viewDidAppear:

override func viewDidAppear(_ animated: Bool) {
    let indexPath:IndexPath = IndexPath(row: 0, section: 0)
    collectionView?.selectItem(at: indexPath, animated: false, scrollPosition: .top)
}

Попробуйте это (Swift 5):

    let indexPath:IndexPath = IndexPath(row: 0, section: 0)
    collectionView?.selectItem(at: indexPath, animated: false, scrollPosition: .top)
Другие вопросы по тегам