gpt4 book ai didi

swift - 在未声明的多个 ImageView 上使用 Uitagesture 识别器

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

我的 swift 代码使用 func addBox 将 ImageView 添加并 append 到 uiview Controller 。我想做的就是当点击其中一个 ImageView 时, func viewClicked 被激活。现在什么也没有发生,也没有任何东西被写入调试区域。

import UIKit

class ViewController: UIViewController {


var ht = -90
var ww = 80
var hw = 80
var arrTextFields = [UIImageView]()
var b7 = UIButton()

override func 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)
for view in self.arrTextFields {
view.isUserInteractionEnabled = true
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(viewClicked)))
}
}



@objc func viewClicked(_ recognizer: UITapGestureRecognizer) {
print("tap")
}


//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

ht += 50
arrTextFields.append(subview)




}
}

最佳答案

您需要启用用户交互

for view in self.arrTextFields {
view.isUserInteractionEnabled = true
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(viewClicked)))
}
<小时/>
@objc func viewClicked(_ recognizer: UITapGestureRecognizer) {
print("tap")
}

关于swift - 在未声明的多个 ImageView 上使用 Uitagesture 识别器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59383412/

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