如何根据selectedSegmentIndex取数据

How to fetch data based on selectedSegmentIndex

我需要根据用户 select 的单元格获取数据。当我集成分段控制时,我开始遇到问题。当用户 selects female/male。主页 UI 将根据段控件上 select 编辑的索引而改变。我目前遇到的问题是当用户执行 select 一个单元格时。我不确定我是否正确使用了 switch 语句,但是没有获取 post 。我什至在数据库中确保每个类别都有一张要获取的虚拟照片。

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

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

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

Cannot assign value of type 'String' to type '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"),

]

我基本上想根据趋势名称和段索引获取数据。

您的数据模型不合适。

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

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

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