【问题标题】:Create TableView Sections according to data in 3 Arrays根据3个数组中的数据创建TableView Sections
【发布时间】:2018-07-19 04:06:38
【问题描述】:

我有 3 个数组,即 todayAry、thisWeekAry、即将到来的Ary,我想根据所有三个数组中的数据创建部分,例如如果所有数组计数大于 0,则为 3 个部分,如果计数为 2,则为两个部分,如果没有数据任何数组然后不创建该部分,那么在 tableView 委托方法中创建它的最佳条件是什么?提供此代码的任何替代方案!! 提前致谢!! 快乐编码!

目前我的代码是:

func numberOfSections(in tableView: UITableView) -> Int {
    if self.todayDataAry.count > 0 {
        if self.thisWeekDataAry.count > 0 {
            if self.upcomingDataAry.count > 0 {
                return 3 // all sections today,this week,upcoming
            } else {
                return 2 //today,this week
            }
        } else {
            if self.upcomingDataAry.count > 0 {
                return 2 //today,upcoming
            } else {
                return 1 //today
            }
        }
    } else {
        if self.thisWeekDataAry.count > 0 {
            if self.upcomingDataAry.count > 0 {
                return 2 //this week, upcoming
            } else {
                return 1 //this week
            }
        } else {
            if self.upcomingDataAry.count > 0 {
                return 1 //upcoming
            } else {
                return 0 //no data
            }
        }
    }
}

【问题讨论】:

    标签: ios arrays iphone swift uitableview


    【解决方案1】:

    创建另一个数组并在其中存储3个数组

    var allDetails = [todayAry, thisWeekAry, upcomingAry]
    var filteredDetails = allDetails.filter { !$0.isEmpty }
    

    然后像这样改变。过滤器移除空数组并返回非空数组计数。

    func numberOfSections(in tableView: UITableView) -> Int {
       return filteredDetails.count
    }
    
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
       return filteredDetails[section].count
    }
    

    你也可以在 cellForRow 方法中做同样的事情

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
       var cell:UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: "cell")
       if cell == nil
       {
         cell = UITableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: "tripHistory")
       }
       cell.textLabel.text = filteredDetails[indexPath.section][indexPath.row]
    }
    

    【讨论】:

    • 谢谢!!但我也想知道创建了哪些部分,因为我想根据每个数组中的计数创建行,即如果创建了今天的部分,那么它的计数是我的行数,但根据您的解决方案,我怎么知道哪些部分是创建?
    • 再次卡在根据计数创建单元格!!你能给我建议根据数据创建单元格吗?因为所有部分根据其计数具有不同的单元格和数据
    • cellForRow 中尝试类似... if indexPath.section == 1 { let cell = tableView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) ...} 这将返回第二个数组。
    • @Sachin 检查更新的答案。如果所有单元格都具有相同的原型单元格,则可以使用它。
    猜你喜欢
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 2022-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多