我正在尝试在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))
}
您的代码对我来说似乎还可以。如果您想触发 didSelectItemat 方法,请使用以下代码。
override func viewDidAppear(_ animated: Bool) {
self.PostsSelectRarityCollectionView(self.PostsSelectRarityCollectionView, didSelectItemAt: IndexPath(row: 0, section: 0))
}
在CollectionViewCell中以编程方式选择CollectionView Loads您应该在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)