如何基于selectedSegmentIndex获取数据

时间:2019-11-30 08:27:17

标签: ios swift firebase-realtime-database uicollectionview uisegmentedcontrol

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

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

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

didSelect上,我收到一条错误消息,指出

  

无法将类型为“字符串”的值分配为类型为“趋势?”

我认为将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获取数据。

1 个答案:

答案 0 :(得分:1)

您的数据模型不合适。

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

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

enum Gender { case male, female }

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

相应地填充数据模型。

然后将一个项传递给详细视图控制器,不需要选定的段索引。

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()
            })
      }
 }