【问题标题】:How to set collection view cell of specific index in iOS Swift?如何在 iOS Swift 中设置特定索引的集合视图单元格?
【发布时间】:2018-12-23 14:51:18
【问题描述】:

在个人资料屏幕中,从用户名、电子邮件 ID、汽车类别的 Firestore 中检索数据。这里的汽车类别是紧凑型、小型、中型和全车。并将 carCategory 参数值存储为字符串(即:CarCategory: "1" 表示 汽车类别"0" 然后它的 紧凑型汽车 if 汽车类别值是“1”然后是小)。

在用户更新页面,car category是一个collection view 流程布局是carousel view
如果汽车类别单元格索引路径值为 1,则显示单元格详细信息而不滚动。

这是我的截图,除了 ::

我的问题是如何在集合视图单元格中加载特定的单元格索引。

这是我目前尝试过的代码::

   **collection view and carousel view**

    var car = [String]()
var carCategory = [ "Compact","small", "Midsize", "Full", "Van/Pick-up" ]
var carCategoryImage = ["compactCar", "smallCar", "mediumCar", "fullCar", "vanPickup"]
var carCategoryMeter = ["3.5 - 4.5m", "2.5 - 3.5m", "4 - 5m", "5 - 5.5m", "5.5 - 6.5m"]

var carCategoryLabel: UILabel?
var carMetersLabel: UILabel?
var carCategoryImageLabel: UIImageView?
var currentPageValue: String?
var currentCell: Int?

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

    return carCategory.count

}

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

    cell.carName.text = carCategory[indexPath.row]
    print("carcategoryIndex\(carCategory)")
    cell.carImage.image = UIImage(named: carCategoryImage[indexPath.row])
    cell.carMeters.text = carCategoryMeter[indexPath.row]




    return cell
}


fileprivate var pageSize: CGSize {
    let layout = self.carCollection.collectionViewLayout as! UPCarouselFlowLayout
    var pageSize = layout.itemSize
    if layout.scrollDirection == .horizontal {
        pageSize.width += layout.minimumLineSpacing
    } else {
        pageSize.height += layout.minimumLineSpacing
    }
    return pageSize
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    let layout = carCollection.collectionViewLayout as! UPCarouselFlowLayout
    let pageSide = (layout.scrollDirection == .horizontal) ? self.pageSize.width : self.pageSize.height
    let offset = (layout.scrollDirection == .horizontal) ? scrollView.contentOffset.x : scrollView.contentOffset.y
    currentPage = Int(floor((offset - pageSide / 2) / pageSide) + 1)
    print("currentpage::::\(currentPage)")


}

fileprivate var currentPage: Int! {
    didSet {

        currentPage = self.currentCell
        print("currentapge::::\(currentPage)")

        let character = self.carCategory[self.currentPage!]
        print("character::::\(character)")

    }
}

   func loadUserData(){


    API.User.observeCurrentUser { (user) in

        if self.userName.text != nil {
            self.userName.text = user.username
            print("username:::\(String(describing: user.username))")
        }
        if let photoUrlString = user.profileImageURL {
            let photoUrl = URL(string: photoUrlString)
            self.profileImage.sd_setImage(with: photoUrl)
        }

        if self.email.text != nil {

            self.email.text = user.email


        }





            switch user.carCategory {

            case "0":

                self.carCategoryLabel?.text = "Compact"
                self.carMetersLabel?.text = "3.5 - 4.5m"
                self.carCategoryImageLabel?.image = UIImage(named: "compactCar")
                self.currentCell = 0
                print("currentCell:::\(String(describing: self.currentCell))")
                self.carCollection.reloadData()

            case "1":

                self.carCategoryLabel?.text = "Small"
                self.carMetersLabel?.text = "2.5 - 3.5m"
                self.carCategoryImageLabel?.image = UIImage(named: "smallCar")
                self.carCategoryLabel?.text = "1"
                self.currentCell = 1
                print("currentCell:::\(String(describing: self.currentCell))")
                self.carCollection.reloadData()


            case "2":

                self.carCategoryLabel?.text = "Midsize"
                self.carMetersLabel?.text = "4 - 5m"
                self.carCategoryImageLabel?.image = UIImage(named: "mediumCar")
                self.currentCell = 2
                print("currentCell:::\(String(describing: self.currentCell))")
                self.carCollection.reloadData()
            case "3":

                self.carCategoryLabel?.text = "Full"
                self.carMetersLabel?.text = "5 - 5.5m"
                self.carCategoryImageLabel?.image = UIImage(named: "fullCar")
                self.currentCell = 3
                print("currentCell:::\(String(describing: self.currentCell))")
                self.carCollection.reloadData()

            case "4":

                self.carCategoryLabel?.text = "Van/Pick-up"
                self.carMetersLabel?.text = "5.5 - 6.5m"
                self.carCategoryImageLabel?.image = UIImage(named: "vanPickup")
                self.currentCell = 4
                print("currentCell:::\(String(describing: self.currentCell))")
                self.carCollection.reloadData()


            default:

                self.carCategoryLabel?.text = ""
                self.carMetersLabel?.text = ""
                self.carCategoryImageLabel?.image = UIImage(named: "")

                break
            }





    }


}//loaduserData

【问题讨论】:

  • 我正确理解您的问题,对于特定的单元格索引,您想显示不同类型的单元格吗?在“cellForItemAt”中检查 indexPath.row 是否等于您想要的确切单元格,并根据需要修改您的单元格,否则显示不同的单元格。
  • @Starsky 感谢您的建议.. 实际上尝试通过在 cellforitem cell.carName.text = carCategory[currentpage] print("carcategoryIndex(carCategory)") cell.carImage.image = UIImage(named: carCategoryImage[currentpage]) cell.carMeters.text = carCategoryMeter[currentpage] 但我什么都没改变
  • 好的,我再次阅读了您的问题,现在我理解了您的问题。您需要使用 collectionView 的方法“selectItem(at:,animated:,scrollPosition:)”。请在下面查看我的解决方案。
  • @Starsky 我看不到你的解决方案..
  • 我当时正在写它)让我知道它是否有帮助?

标签: ios swift uicollectionview carousel indexpath


【解决方案1】:

这是如何做到的:

override func viewDidLoad() {
    super.viewDidLoad()

    collectionView.selectItem(at: [0, currentCell], animated: false, scrollPosition: .centeredHorizontally)
    }

当你加载你的 viewController 时,我假设你设置了 currentCell?我看不到你原来的 viewDidLoad()viewDidAppear() 函数。如果您从以前的 viewController 实例化此 viewController,则从那里设置您的 currentCell。如果您选择此 viewController,请将其设置在 prepareForSegue 方法中。

【讨论】:

    【解决方案2】:

    下面的代码可能会在这个场景中帮助你

    // MARK: - Collectionview delegates
        extension FaqcategoriesViewController : UICollectionViewDelegate, UICollectionViewDataSource , UICollectionViewDelegateFlowLayout{
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return (Global.shared.FAQsCategoriesList?.list.count)!
        }
    
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "faqcategoriesCollectioncell",
                                                          for: indexPath) as! FAQCategoryCollectionViewCell
            cell.configure(data: (Global.shared.FAQsCategoriesList?.list[indexPath.row])!)
            return cell
        }
        func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    
            let storyBoard = Utilities.getStoryboard(name: SBMEMBERSANDCOMMISSIONS)
            let nextView  = storyBoard.instantiateViewController(withIdentifier: "faq") as! FAQViewController
            nextView.id = indexPath.row
            self.navigationController?.pushViewController(nextView, animated: false)
        }
    
        func collectionView(_ collectionView: UICollectionView,
                            layout collectionViewLayout: UICollectionViewLayout,
                            sizeForItemAt indexPath: IndexPath) -> CGSize {
            let collectionViewSize = collectionView.frame.size.width
            print(self.view.frame.width)
            print(collectionView.frame.size.width)
            print( "width: \(collectionViewSize/2 - 20) height: \(collectionView.frame.size.height/3.3)")
            return CGSize(width: collectionViewSize/2 - 5, height: collectionView.frame.size.height/3.3)
        }
    
        func collectionView(_ collectionView: UICollectionView,
                            layout collectionViewLayout: UICollectionViewLayout,
                            minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
            return 1.0
        }
    
        func collectionView(_ collectionView: UICollectionView, layout
            collectionViewLayout: UICollectionViewLayout,
                            minimumLineSpacingForSectionAt section: Int) -> CGFloat {
            return 1.0
        }
    
    }
    

    【讨论】:

    • 这将为您提供平方单元格。您可以通过编辑以下行来更改它们
    • func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let collectionViewSize = collectionView.frame.size.width print(self.view.frame.width)打印(collectionView.frame.size.width)打印(“宽度:(collectionViewSize/2 - 20)高度:(collectionView.frame.size.height/3.3)”)返回CGSize(宽度:collectionViewSize/2 - 5,高度: collectionView.frame.size.height/3.3) }
    • 感谢您的回答。在选择中,我需要滚动选择。我不想在这里滚动。无需滚动如何在集合中加载特定的单元格索引路径。看看我的截图
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 2018-12-23
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多