ios - 如何根据selectedSegmentIndex取数据

标签 ios swift firebase-realtime-database uicollectionview uisegmentedcontrol

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

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

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

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"),

]

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

最佳答案

您的数据模型不合适。

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

声明一个包含 Collection View 中一个项目的所有信息的结构,并为性别信息添加一个枚举。

enum Gender { case male, female }

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

相应地填充数据模型。

然后将一个项传递给详细 View Controller ,不需要选择的段索引。

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

在有问题的 View Controller 中声明一个属性

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

关于ios - 如何根据selectedSegmentIndex取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59114493/

相关文章:

iphone - 如果用户选择从游戏内部邀请玩家,我如何通过自动匹配来区分这一点

ios - 如何将拖动移动功能添加到转换后的 View ?

ios - 位于中心的水平条形图标签

ios - 如何使 collectionView 中的可折叠标题与 Facebook 标题相同?

ios - 如何在 iOS 上以编程方式将 Facebook 帖子可见性更改为 "public"

ios - CKDatabaseSubscription 不推送通知

ios - iOS:打开具有已填充日期的“日历”应用“新事件”屏幕

javascript - 如何在 Firebase 中添加带有电子邮件和密码的用户名?

java - Android-Expected a List while deserializing, but got a class java.util.HashMap

android - 从 Android 中的 firebase 获取恒定数据