gpt4 book ai didi

Swift CollectionView 部分类别

转载 作者:行者123 更新时间:2023-11-28 07:39:48 25 4
gpt4 key购买 nike

我正在尝试在 Collection View 中创建鸡尾酒菜单。来自 API 的数据包含按类别(甜味、果味等)分组的鸡尾酒和鸡尾酒数组之外的类别图像。我想要实现的布局如下图所示。

使用我编写的代码,我成功地对鸡尾酒进行了分组,但是我不确定如何将类别图像显示为每个部分的第一个单元格。

实现此目标的最佳方法是什么?

来自 API 的数据:

[ 
   {
      "signatureCocktailSets":[
         {
            "cocktails":[
               {
                  "id":1,
                  "cocktail":1,
                  "category":1,
                  "image":"*****/fruity.png",
                  "cocktailid":1,
                  "name":"Fruit & Fibre",
                  "description":"Throwing fresh Raspberry Gin and Black Raspberry Liquer together, mixed with Passionfruit Puree to give a crisp and fruity taste.",
                  "ingredients":"\nEdinburgh Raspberry\nChambord\nApple juice\nPassionfruit puree\nSugar syrup",
                  "cocktailImage":"*****/Fruit+%26+Fibre.jpg",
                  "property":"Fruity"
               },
               {
                  "id":1,
                  "cocktail":2,
                  "category":1,
                  "image":"*****/fruity.png",
                  "cocktailid":2,
                  "name":"Beach Blend",
                  "description":"A perfect balance of Coconut Rum Pineapple Juice and Banana Liquer takes you back to the Sunny Beaches.",
                  "ingredients":"Malibu\nPineapple juice\nBanana liqueur\nCaramel syrup",
                  "cocktailImage":"*****/Beach+Blend.jpg",
                  "property":"Fruity"
               },
               {
                  "id":1,
                  "cocktail":3,
                  "category":1,
                  "image":"*****/fruity.png",
                  "cocktailid":3,
                  "name":"Passion Berry",
                  "description":"Passionfruit based flavour with the warmth of Gin we all Love. Shaken with fresh Raspberries to add then extra rich fruity taste.",
                  "ingredients":"Tanqueray\nPassoa\nPassionfruit puree\nLemon Juice\nFresh raspberries\nSugar syrup",
                  "cocktailImage":"*****/Passion+Berry.jpg",
                  "property":"Fruity"
               }
            ],
            "SignatureCocktailSetImageURL":"*****/fruity.png"
         },
         {
            "cocktails":[
               {
                  "id":2,
                  "cocktail":4,
                  "category":2,
                  "image":"*****/indulgent.png",
                  "cocktailid":4,
                  "name":"Forest Gataux",
                  "description":"A rich taste of berries, with an almond flavour at the end. The perfect dessert, go ahead treat yourself. ",
                  "ingredients":"Chambord\nSmirnoff\nDisaronno\nStrawberry syrup",
                  "cocktailImage":"*****/Forest+Gateaux.jpg",
                  "property":"Indulgent"
               },
               {
                  "id":2,
                  "cocktail":5,
                  "category":2,
                  "image":"*****/indulgent.png",
                  "cocktailid":5,
                  "name":"Mint Moment",
                  "description":"A Minty taste with a rich coffee and cream base brings Indulgent Nights to life  ",
                  "ingredients":"Baileys\nCr\u00e8me de menthe\nKahlua",
                  "cocktailImage":"*****/Mint+Moment.jpg",
                  "property":"Indulgent"
               },
               {
                  "id":2,
                  "cocktail":6,
                  "category":2,
                  "image":"*****/indulgent.png",
                  "cocktailid":6,
                  "name":"Nutty Monk",
                  "description":"A smooth Hazlenut and Cream blend will leave your palette feeling enlivened ",
                  "ingredients":"Baileys\nFrangelico\nKahlua",
                  "cocktailImage":"*****/Nutty+Monk.jpg",
                  "property":"Indulgent"
               }
            ],
            "SignatureCocktailSetImageURL":"*****/indulgent.png"
         },
         {
            "cocktails":[
               {
                  "id":3,
                  "cocktail":7,
                  "category":3,
                  "image":"*****/sour.png",
                  "cocktailid":7,
                  "name":"Tropic Tequila",
                  "description":"Tequila Fan? This sour blend of Patron Silver Tequila, Pineapple Juice will leave a fruity kick to remember",
                  "ingredients":"Patron Silver\nPineapple juice\nLemon Juice\nSugar syrup",
                  "cocktailImage":"*****/Tropic+Sour.jpg",
                  "property":"Sour"
               },
               {
                  "id":3,
                  "cocktail":8,
                  "category":3,
                  "image":"*****/sour.png",
                  "cocktailid":8,
                  "name":"Sloe & Sour",
                  "description":"Blended with Gordon's Sloe Gin, these bitter berries are ephasised by the Lemon Juice, a zesty tingle to your tastebuds",
                  "ingredients":"Gordon's Sloe\nPassoa\nPassionfruit puree\nLemon juice\nSugar syrup",
                  "cocktailImage":"*****/Sloe+%26+Sour.jpg",
                  "property":"Sour"
               },
               {
                  "id":3,
                  "cocktail":9,
                  "category":3,
                  "image":"*****/sour.png",
                  "cocktailid":9,
                  "name":"Kentucky Twist",
                  "description":"Like the Buffalo, this is a strong bodied cocktail. Blending up a fruity yet sour edge, giving just a slight nudge but nothing you can't handle",
                  "ingredients":"Buffalo Trace\nChambord\nGordon's Pink\nLemon juice\nSugar syrup\nApple juice",
                  "cocktailImage":"*****/Kentucky+Twist+600x600.jpg",
                  "property":"Sour"
               }
            ],
            "SignatureCocktailSetImageURL":"*****/sour.png"
         },
         {
            "cocktails":[
               {
                  "id":4,
                  "cocktail":10,
                  "category":4,
                  "image":"*****/sweet.png",
                  "cocktailid":10,
                  "name":"Rhubard Passion",
                  "description":"Built around a poupular flavour, this bitter Rhubarb has been sweetened up with Passionfruit to give you a refreshing and satisyfing flavour",
                  "ingredients":"Slingsby Rhubarb\nPassoa\nLemon Juice\nSugar syrup\nSoda top",
                  "cocktailImage":"*****/Rhubarb+Passion.jpg",
                  "property":"Sweet"
               },
               {
                  "id":4,
                  "cocktail":11,
                  "category":4,
                  "image":"*****/sweet.png",
                  "cocktailid":11,
                  "name":"Tai Spice",
                  "description":"Spiced Dark Rum, sweetened with and almond and orange Liqueur Based upon a Tiki Classic this sweet selection with leave you feeling savoured",
                  "ingredients":"Kracken\nDisaronno\nCointreau\nLime juice\nSugar syrup",
                  "cocktailImage":"*****/Tai+Spice.jpg",
                  "property":"Sweet"
               },
               {
                  "id":4,
                  "cocktail":12,
                  "category":4,
                  "image":"*****/sweet.png",
                  "cocktailid":12,
                  "name":"Fibre-Day",
                  "description":"If you like fresh fruit this is the one for you, Kurrants, Watermelon, Peach and crisp Apple. This is bound to take you back to that cocktail bar abroad. ",
                  "ingredients":"Absolut Kurrant\nMidori\nArchers\nApple juice\nLemon juice",
                  "cocktailImage":"*****/Fibre+Day.jpg",
                  "property":"Sweet"
               }
            ],
            "SignatureCocktailSetImageURL":"*****/sweet.png"
         }
      ]
   }
]

我要实现的目标:

enter image description here

我目前拥有的:

enter image description here

代码:

import UIKit
import SDWebImage

struct cocktailsStruct: Decodable {
var cocktailid: Int
var name: String
var description: String
var ingredients: String
var cocktailImage: URL
}

struct signatureCocktailSetsStruct: Decodable {
var cocktails:[cocktailsStruct]
var SignatureCocktailSetImageURL: String
}

struct signatureCocktailStruct : Decodable {
var signatureCocktailSets: [signatureCocktailSetsStruct]
}

var signatureCocktailArray: [signatureCocktailStruct]!

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

var numberOfSections: Int = 4


@IBOutlet var collectionViewHeight: NSLayoutConstraint!
@IBOutlet var collectionView: UICollectionView!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
collectionView.register(UINib(nibName: "cocktail", bundle: nil), forCellWithReuseIdentifier: "cell")
let url = URL(string: "https://www.******")

URLSession.shared.dataTask(with: url!) { (data, reponse, error) in

do {
signatureCocktailArray = try JSONDecoder().decode([signatureCocktailStruct].self, from: data!)
print(signatureCocktailArray[0].signatureCocktailSets[0].SignatureCocktailSetImageURL)
print(signatureCocktailArray[0].signatureCocktailSets.count)
self.numberOfSections = signatureCocktailArray[0].signatureCocktailSets.count
DispatchQueue.main.async {
self.collectionView.reloadData()
}

} catch {
print("Error \(error)")
}
}.resume()

self.view.layoutIfNeeded()
collectionViewHeight.constant = collectionView.contentSize.height
}

func numberOfSections(in collectionView: UICollectionView) -> Int {

return numberOfSections
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

return CGSize(width: self.collectionView.frame.width / 2, height: self.collectionView.frame.width / 2)
}

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! cocktail
if(signatureCocktailArray != nil){
cell.image.sd_setImage(with: URL(string: "\(signatureCocktailArray[0].signatureCocktailSets[indexPath.section].cocktails[indexPath.row].cocktailImage)"), completed: nil)
}
return cell
}
}

最佳答案

一步一步走

1) 根据服务器的响应更新项目数

 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return signatureCocktailArray[0].signatureCocktailSets[indexPath.section].cocktails.count + 1
}

2) 检查 indexPath.row 如果为零则设置默认值

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! cocktail
if(signatureCocktailArray != nil) {
if indexPath.row == 0 {
cell.image.sd_setImage(with: URL(string: "\(signatureCocktailArray[0].signatureCocktailSets[indexPath.section]. SignatureCocktailSetImageURL)"), completed: nil)
} else {
cell.image.sd_setImage(with: URL(string: "\(signatureCocktailArray[0].signatureCocktailSets[indexPath.section].cocktails[indexPath.row-1].cocktailImage)"), completed: nil)
}}
return cell
}

注意:如果此时实现了didSelect方法,请考虑将条件也放在那里,以避免崩溃

希望对你有帮助

关于Swift CollectionView 部分类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52587862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com