我使用代码填充UIImage数组并成功将它们添加到UIScrollView中。我想识别点击的图像,以便我可以相应地执行操作。
感谢您的指导和时间。
这是我到目前为止的代码:
override func viewDidLoad() {
super.viewDidLoad()
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.imageTapped(_:)))
}
func loadImagePicker(){
var contentWidth: CGFloat = 0.0
let imageWidth: CGFloat = 100.0
let imageHeight: CGFloat = 100.0
for x in 0...2 {
let image = UIImage(named: "item\(x).png")
let imageView = UIImageView(image: image)
imageView.isUserInteractionEnabled = true
myData.images1.append(imageView)
var newX: CGFloat = 0.0
newX = 10 + imageWidth * CGFloat(x) + (10 * CGFloat(x))
contentWidth += newX
scrollView.addSubview(imageView)
imageView.frame = CGRect(x: newX, y: scrollView.frame.size.height, width: imageWidth, height: imageHeight)
imageView.contentMode = .scaleToFill
}
print(myData.images1.count)
scrollView.clipsToBounds = false
scrollView.contentSize = CGSize(width: contentWidth, height: scrollView.frame.size.height)
imagePickerView.isHidden = false
}
答案 0 :(得分:2)
为您的imageView添加手势识别器,如下所示:
//Instance Variable
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.imageTapped(_:)))
tapGestureRecognizer.numberOfTapsRequired = 1
tapGestureRecognizer.numberOfTouchesRequired = 1
func loadImagePicker(){
// .....
for 0..<2 { //Assuming there are two images
// .....
// .....
imageView.addGestureRecognizer(tapGestureRecognizer)
}
}
func imageTapped(_ sender: UITapGestureRecognizer) {
let tappedImageView = sender.view as! UIImageView
let index = tappedImageView.tag // Do anything with the index by using it in your array
}
答案 1 :(得分:0)
将您的tapGestureRecognizer
设为全局或将其移至loadImagePicker
功能。
将isUserInteractionEnabled
设置为true后,添加手势
通过调用imageView
的识别器
imageView.addGestureRecognizer(tapGestureRecognizer)
。
imageTapped
函数,该函数接受UITapGestureRecognizer
sender as? UIImageView