如何基于selectedSegmentIndex获取数据

问题描述 投票:0回答:1

我需要根据用户选择的单元格来获取数据。当我集成分段控制时,我开始遇到问题。当用户选择女性/男性时。主界面将根据在细分控件上选择的索引而变化。我当前遇到的问题是用户确实选择了一个单元格。我不确定我是否正确使用switch语句,但是没有获取帖子。我什至在数据库中确保每个类别都有要提取的虚拟照片。

这里是主页代码,可以正常工作,但是代码可能与某些代码有关。

现在根据下面的答案编辑代码

didSelect上,我现在看到一个错误,指出

无法将'String'类型的值分配给'Trend?']

[我认为将name添加到vc.trend将能够获取数据,因为在我们甚至实现segmentedControl之前,didSelect仅通过使用趋势名称即可正常工作,然后我们将根据趋势获取照片名称。

       case 0: vc.trend.name = femaleTrends[indexPath.row]
        case 1: vc.trend.name = maleTrends[indexPath.row]

   var selectedSegmentIndex = 0
   var header: HomeViewHeaderReusableView?


// Reload data when index changes
 func handleSegControlTapped(for header: HomeViewHeaderReusableView) {
        selectedSegmentIndex = header.segmentedControl!.selectedSegmentIndex
        collectionView.reloadData()
    }

   // Return the number of trend categories availabe
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {


        switch selectedSegmentIndex {
        case 0: return femaleTrends.count
        case 1: return maleTrends.count
        default: print("opps, cant load data")
           return 0
        }

    }

    //Display the current trend image place holder and labels
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "homeViewCell", for: indexPath) as! CurrentTrendsCell

        switch selectedSegmentIndex {
        case 0: cell.trendsLabel.text = femaleTrends[indexPath.row]
        cell.trendsImageView.image = femaleImages[indexPath.row]


        case 1: cell.trendsLabel.text = maleTrends[indexPath.row]
        cell.trendsImageView.image = maleImages[indexPath.row]

        default: break

        }

        return cell


    }


    // Selected HomeView Cell data will pass to second home view controller
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        let storyboard = UIStoryboard(name: "Main", bundle: nil)

        let vc = storyboard.instantiateViewController(withIdentifier: "selectedHomeCellView") as! SelectedCellHomeViewController

        switch selectedSegmentIndex {
        case 0: vc.trend = femaleTrends[indexPath.row]
        case 1: vc.trend = maleTrends[indexPath.row]
            default: break
        }

        self.navigationController?.pushViewController(vc, animated: true)

       self.navigationController?.navigationBar.backIndicatorImage = #imageLiteral(resourceName: "BackButton")
       self.navigationItem.backBarButtonItem = UIBarButtonItem(title: nil, style: UIBarButtonItem.Style.plain, target: nil, action: nil)

    }

这是有问题的viewController代码




   // Display uploaded photos
   func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return posts.count
   }

   // Get a photo cell
   func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "userPhotos", for: indexPath) as! PostCollectionViewCell

       cell.posts = posts[indexPath.item]


       return cell
   }


var trend: Trend!


func fetchPosts() {
  print("fetching post")

   self.trendDetails = trend.details
   self.trendName = trend.name

  switch trend.gender  {

      case .female:
       FEMALE_TRENDS_REF.child((trend.childValue)).observe(.childAdded) { (snapshot) in
             let postId = snapshot.key
             Database.fetchPost(with: postId, completion: { (post) in
                 self.posts.append(post)
                 self.posts.sort(by: { (post1, post2) -> Bool in
                 return post1.creationDate > post2.creationDate
             })
             self.collectionView?.reloadData()
          })

   }


           case .male:
               MALE_TRENDS_REF.child((trend.childValue)).observe(.childAdded) { (snapshot) in
              let postId = snapshot.key
              Database.fetchPost(with: postId, completion: { (post) in
                  self.posts.append(post)
                  self.posts.sort(by: { (post1, post2) -> Bool in
                  return post1.creationDate > post2.creationDate
              })
              self.collectionView?.reloadData()

           })


     }

}

   }

 let femaleTrends = [

Trend(name: "Animal Prints", details: "girl prints", image: UIImage(named: "Animal Prints"), gender: .female, childValue: "animalprints"),


Trend(name: "Dark Romance", details: "Darkromance text.",image: UIImage(named: "Dark Romance"),gender: .female, childValue: "darkromance"),


Trend(name: "Green", details: "Green text.",image: UIImage(named: "Green"),gender: .female, childValue: "green"),]




    let maleTrends = [

Trend(name: "Animal Prints", details: "mens animal prints",image:UIImage(named: "Aprint"),gender: .male , childValue: "animalprints"),


Trend(name: "Corduroy", details: "mens corduroy",image: UIImage(named: "CorduroyM"),gender: .male, childValue: "corduroy"),


Trend(name: "Earth Tones", details: "mens earth tones",image: UIImage(named: "Earth Tones"),gender: .male, childValue: "earthtones"),

]

我基本上是想根据趋势名称和segmentIndex获取数据。

ios swift firebase-realtime-database uicollectionview uisegmentedcontrol
1个回答
1
投票

您的数据模型不合适。

强烈建议您不要使用多个数组作为数据源。

在集合视图中声明一个包含一个项目的所有信息的结构,并为性别信息添加一个枚举。

enum Gender { case male, female }

struct Trend {
   let name : String
   let details : ...
   let image : ...
   let gender : Gender
   // other properties 
}

相应地填充数据模型。

然后将one项目传递到详细视图控制器,不需要选择的段索引。

switch selectedSegmentIndex {
    case 0: vc.trend = femaleTrends[indexPath.row]
    case 1: vc.trend = maleTrends[indexPath.row]
    default: break
}

有问题的视图控制器中声明属性

var trend : Trend!

并根据gender信息获取帖子

func fetchPosts() {
   print("fetching post")

   self.trendDetails = trend.details ?? ""
   self.trendName = trend.name ?? ""

   switch trend.gender  {

       case .female:
           FEMALE_TRENDS_REF.child((trend.childValue)!).observe(.childAdded) { (snapshot) in
              let postId = snapshot.key
              Database.fetchPost(with: postId, completion: { (post) in
                  self.posts.append(post)
                  self.posts.sort(by: { (post1, post2) -> Bool in
                  return post1.creationDate > post2.creationDate
              })
              self.collectionView?.reloadData()
           })
       case .male:
           MALE_TRENDS_REF.child((trend.childValue)!).observe(.childAdded) { (snapshot) in
               let postId = snapshot.key
               Database.fetchPost(with: postId, completion: { (post) in
                   self.posts.append(post)
                   self.posts.sort(by: { (post1, post2) -> Bool in
                   return post1.creationDate > post2.creationDate
               })
               self.collectionView?.reloadData()
            })
      }
 }
© www.soinside.com 2019 - 2024. All rights reserved.