Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 识别已点击的UIImageView并在数组中获取其索引_Ios_Swift_Xcode - Fatal编程技术网

Ios 识别已点击的UIImageView并在数组中获取其索引

Ios 识别已点击的UIImageView并在数组中获取其索引,ios,swift,xcode,Ios,Swift,Xcode,现在我有代码为数组中的每个图像生成TapGestureRecognitor,我要做的是返回用户点击的图像索引。实现这一目标最简单的方法是什么?我是Swift新手,所以我从youtube教程中获得了部分信息,但我真的不知道如何使用手势识别器:/ 这就是我到目前为止所做的(简化为仅包括相关内容): 您可以非常轻松地执行此操作,因为您已经创建了一个UIImageView数组,并且您只需要数组中点击的imageView的索引,您只需要使用方法firstIndex(其中:,以下是代码: @iAction

现在我有代码为数组中的每个图像生成TapGestureRecognitor,我要做的是返回用户点击的图像索引。实现这一目标最简单的方法是什么?我是Swift新手,所以我从youtube教程中获得了部分信息,但我真的不知道如何使用手势识别器:/

这就是我到目前为止所做的(简化为仅包括相关内容):


您可以非常轻松地执行此操作,因为您已经创建了一个
UIImageView
数组,并且您只需要数组中点击的imageView的索引,您只需要使用方法
firstIndex(其中:
,以下是代码:

@iAction func imageTapped(识别器:UIGestureRecognitizer){
让houseImages=[self.right1,self.right2,self.right3]
如果let view=recognizer.view as?UIImageView{
让indexOfSelectedImageView=housemages.firstIndex(其中:{$0==view})
打印(indexOfSelectedImageView)
}
}

由于您已经有了一个存储所有图像的数组,因此通过在
houseImages
中搜索图像索引,可以很容易地知道已点击了哪些图像(和索引)

由于使用
firstIndex(其中:[……])
获取索引不需要复杂的验证,因此我建议在您的案例中使用
firstIndex(of:UIImageView)

@IBAction func imageTapped(recognizer: UIGestureRecognizer) {
    guard let tappedView = recognizer.view as? UIImageView else {
        return
    }
    let index = self.houseImages.firstIndex(of: tappedView)
    print("House image index = \(index)")
}
@IBAction func imageTapped(recognizer: UIGestureRecognizer) {
    guard let tappedView = recognizer.view as? UIImageView else {
        return
    }
    let index = self.houseImages.firstIndex(of: tappedView)
    print("House image index = \(index)")
}