簡體   English   中英

一個單元格中的UIViewController使用Swift一次顯示兩個單元格

[英]UIViewController in One Cell show Two Cells at once with Swift

我有相同的代碼,結果不是那樣的。 我是新來的迅速。 我嘗試了不同的方法,但是沒有用。 幫助解決問題並獲得期望的結果。

import UIKit

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

    let arr = ["aa","bb","cc","d#d","ee","ff"]

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return arr.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {


        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath as IndexPath) as! MyCollectionViewCell


        let fullNameArr = arr[indexPath.item].split(separator: "#") as [AnyObject]


        let firstName = fullNameArr as! [String]

        let os = firstName.count

        if (os > 1){


            if os == 2{

                cell.myLabel.text = firstName[0]

                cell.backgroundColor = UIColor.red


            }else{

                cell.myLabel.text = firstName[1]

                cell.backgroundColor = UIColor.blue

            }

        }else{

            cell.myLabel.text = arr[indexPath.item]

            cell.backgroundColor = UIColor.orange

        }

        return cell

    }

}

這是它的樣子

在此處輸入圖片說明

這是最終的樣子

在此處輸入圖片說明

因為您期望的是d#d = 2d,但是您將collectioncell的計數設置為1。您可以先簡單地處理數組,並保留所有代碼

var arr = ["aa","bb","cc","d#d","ee","ff"] // Change let to var
// Break all x#x -> x# + x#
arr = arr.reduce([]) { (res, str) -> [String] in
    var result = res
    var comps = str.components(separatedBy: "#")
    if comps.count > 1 {
        comps = comps.map({$0 + "#"})
    }
    result.append(contentsOf: comps)
    return result
}

請仔細閱讀集合視圖單元委托和數據源方法,以及其工作方式。

根據您的代碼,看來如果字符串具有#值,則應將其分開並應添加單元格編號。

為此,請在調用tableview方法之前實現#分隔符邏輯。 永遠記住,將根據numberOfItemsInSection數據源方法中返回的項目數創建單元格。

使用下面的代碼獲取更新的數組:

let newArr:[String] = [String]()
for data in arr {
    let numberOfStr = data.split(separator: "#") as [String]
    if numberOfStr.count > 1 {
         for data in numberOfStr {
              newArr.append(data)
         }
    } else {
        newArr.append(data)
    }
}

與其直接使用字符串數組,不如先建立模型,然后求解邏輯,直接將模型數組提供給collectionview以設置數據

將包含數據的模型類

class Item {
  var value: String?
  var isColored: Bool?

  init(value: String?, isColored: Bool) {
    self.value = value
    self.isColored = isColored
  }
}

解決上述問題的邏輯功能

func getRequiredData(_ arr: [String]) -> [Item] {
      var newItems = [Item]()
      arr.forEach({newItems.append(Item.init(value: $0, isColored: false))})

      newItems.forEach { (item) in
        if /item.value?.contains("#") {
          let dividedItems = (/item.value).split(separator: "#")
          dividedItems.forEach({newItems.append(Item.init(value: /String($0 ?? ""), isColored: true))})
        }
      }
      let filteredArray = newItems.filter({!(/$0.value?.contains("#"))})
      let sortedArray = filteredArray.sorted(by: { /$0.value < /$1.value })
      return sortedArray
}

現在,您可以將[Item]數組提供給從上述函數獲得的集合

let items = getRequiredData(["aa","bb","cc","d#d","ee","ff"])

使用項目作為數據進行collectionview,並根據項目的值(例如

cell.myLabel.text = self.items[indexPath.row].value
cell.backgroundColor = (self.items[indexPath.row].value ?? false) ? UIColor.orange : UIColor.blue

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM