我试图在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
}
}
但这不起作用......我希望有人知道我做错了什么......
提前致谢
更新 由于Razib的回答,这对我现在很有用:
override func viewWillAppear(_ animated: Bool) {
self.collectionView(PostsSelectRarityCollectionView, didSelectItemAt: IndexPath(row: 0, section: 0))
}
答案 0 :(得分:2)
要在加载Collectionview时以编程方式选择CollectionViewCell中的第一个项目,应在viewDidAppear中进行编码:
True
答案 1 :(得分:0)
你的代码对我来说似乎没问题。如果您想触发 didSelectItemAt 方法,请使用以下代码。
override func viewDidAppear(_ animated: Bool) {
self.PostsSelectRarityCollectionView(self.PostsSelectRarityCollectionView, didSelectItemAt: IndexPath(row: 0, section: 0))
}
答案 2 :(得分:0)
尝试一下(快速5):
let indexPath:IndexPath = IndexPath(row: 0, section: 0)
collectionView?.selectItem(at: indexPath, animated: false, scrollPosition: .top)