gpt4 book ai didi

swift - 通过按下来更改空数组中 uiimageview 的颜色

转载 作者:行者123 更新时间:2023-11-30 10:30:03 24 4
gpt4 key购买 nike

下面我的快速代码有一个按钮,当触摸时,会在 View Controller 上放置一个 ImageView 。我唯一想做的事情是,当一个单独的 ImageView 而不是所有 ImageView 只是一个选择被触摸时,我想仅在触摸时将颜色从紫色更改为蓝色,并且一次一个。

enter image description here

import UIKit

class ViewController: UIViewController {

var count: Int = 0
var ht = -90
var ww = 80
var moveCounter = 0
var counter = 0
var arrTextFields = [UIImageView]()
var b7 = UIButton()


override func viewDidLoad() {
super.viewDidLoad()

[b7].forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
view.addSubview($0)
$0.backgroundColor = .systemOrange
}

b7.frame = CGRect(x: view.center.x-115, y: view.center.y + 200, width: 70, height: 40)
b7.addTarget(self, action: #selector(addBOx), for: .touchUpInside)

}

//func that adds imageview.
@objc func addBOx() {

let subview = UIImageView()

subview.isUserInteractionEnabled = true
arrTextFields.append(subview)
view.addSubview(subview)


subview.frame = CGRect(x: view.bounds.midX - 0, y: view.bounds.midY + CGFloat(ht), width: CGFloat(ww), height: 35)


subview.backgroundColor = .purple
subview.tag = count

count += 1
ht += 50
arrTextFields.append(subview)



}}

最佳答案

您已将 ImageView 的 isUserInteractionEnabled 属性设置为 true。要响应触摸事件,请创建 UITapGestureRecognizer并将其添加到 ImageView 中,如下所示:

let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageViewTapped))
subview.addGestureRecognizer(gestureRecognizer)

然后在 imageViewTapped 方法中,您可以从发送者参数中提取 ImageView :

@objc func imageViewTapped(sender: UITapGestureRecognizer) {
if let imageView = sender.view as? UIImageView {
// Change the imageView's background here
}
}

关于swift - 通过按下来更改空数组中 uiimageview 的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59332654/

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