gpt4 book ai didi

ios - 从 Collection View 返回正确的图像

转载 作者:行者123 更新时间:2023-11-28 05:38:13 24 4
gpt4 key购买 nike

我创建了一个显示多张图片的 Collection View 。但是,当我点击其中一个单元格时,它没有填充正确的图像。

这是我的图片集:

let stickers: [UIImage] = [
UIImage(named: "cow")!,
UIImage(named: "chicken")!,
UIImage(named: "pig")!,
]

我设置了一个默认图片:

var activeSticker = UIImage(named: "cow")

此函数设置 Collection View 并将上面的所有图像显示为单独的单元格:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
cell.stickerImage.image = stickers[indexPath.item]
cell.backgroundColor = UIColor(white: 1, alpha: 0.9)
cell.translatesAutoresizingMaskIntoConstraints = false
cell.contentMode = .scaleAspectFill
cell.clipsToBounds = true
cell.layer.cornerRadius = 7
let addSticker = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
addSticker.addTarget(self, action: #selector(addStickerTapped), for: UIControl.Event.touchUpInside)
activeSticker = cell.stickerImage.image
cell.addSubview(addSticker)
return cell
}

此函数当前将图像添加到 View ,但它不是点击的单元格,我不确定它是如何设置值的。

@IBAction func addStickerTapped() -> Void {
print("Hello Sticker Button")
let image = activeSticker
let imageView = UIImageView(image: image!)
imageView.frame = CGRect(x: 100, y: 100, width: 100, height: 200)
imageView.contentMode = .scaleAspectFit
imageView.isUserInteractionEnabled = true
self.view.addSubview(imageView)
//Imageview on Top of View
self.view.bringSubviewToFront(imageView)
selectedImageView = imageView
}

最佳答案

首先,将 CollectionViewCell 的 布局的所有代码从 cellForItemAt 移动到 awakeFromNib()

接下来,在 CollectionViewCell 的 xib 本身中创建 addSticker button 而不是每次都在 cellForItemAt.

此外,使用 closure 来处理 addSticker 按钮上的 tap 事件

所以,CollectionViewCell 看起来像,

class CollectionViewCell: UICollectionViewCell {
@IBOutlet weak var stickerImage: UIImageView!
var handler: (()->())?

override func awakeFromNib() {
super.awakeFromNib()
self.backgroundColor = UIColor(white: 1, alpha: 0.9)
self.contentMode = .scaleAspectFill
self.clipsToBounds = true
self.layer.cornerRadius = 7
}

@IBAction func onTapAddStickerButton(_ sender: UIButton) {
self.handler?()
}
}

现在,在 cellForItemAt 中创建 CollectionViewCell 的实例,并设置在点击 addSticker 后调用的 handler > 按钮,即

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
let sticker = stickers[indexPath.item]
cell.stickerImage.image = sticker
cell.handler = {
self.activeSticker = sticker
//add the code after tapping the addSticker here...
}
return cell
}

我对您在 addStickerTapped() 方法中尝试做的事情有点困惑。请澄清更多以便更好地理解。

关于ios - 从 Collection View 返回正确的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57864254/

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