gpt4 book ai didi

ios - 显示从 url 到 Collection View Swift 单元格的 3 张图像

转载 作者:行者123 更新时间:2023-11-30 13:25:16 25 4
gpt4 key购买 nike

我从 API 请求了 3 个图像 URL。我想在 Collection View 上的单元格中显示 url 图像中的 3 张图像。我是快速编程新手

这是我的代码

class MainCollectionViewController: UICollectionViewController {

override func viewDidLoad() {
super.viewDidLoad()

Alamofire.request(.POST, "URL").responseJSON { response in

if let value = response.result.value {

let json = JSON(value)

let data = json["data"].arrayValue

for datas in data {

let result = datas["image"].stringValue

print(result)

}
}
}
}

override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}

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

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MainCollectionViewCell

return cell
}
}

我的 ImageView 位于名为 mainImageView 的 mainCollectionViewCell 上

最佳答案

在代码中编写如下内容,

class MainCollectionViewController: UICollectionViewController {

var myImageArray : NSMutableArray = NSMutableArray()

override func viewDidLoad() {
super.viewDidLoad()

Alamofire.request(.POST, "URL").responseJSON { response in

if let value = response.result.value {

let json = JSON(value)

let data = json["data"].arrayValue

for datas in data {

let result = datas["image"].stringValue

self.myImageArray.addObject(result)
print(result)

}
}
}
}

override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}

override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.myImageArray.count
}

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MainCollectionViewCell

let url = NSURL(string: self.myImageArray.objectAtIndex(indexPath.row) as String)
let data = NSData(contentsOfURL: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check
cell.mainImageView.image = UIImage(data: data!)

return cell
}
}

希望这对你有帮助:)

关于ios - 显示从 url 到 Collection View Swift 单元格的 3 张图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37290382/

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