我已经以编程方式将 imageViews 中的图像添加到数组中 5 个对象的 for 循环中的父 scrollView。每个 imageView 都有一个 TapGestureRecognizer,所以我可以点击它们,它们会调用一个函数。
我希望函数将 scrollView 中的 setContentOffset 设置到点击图像的 x 值中心的位置。我不确定如何从点击的 imageView 中提取 CGPoint。任何帮助都会很棒。
这是我目前所拥有的:
override func viewDidLoad() {
super.viewDidLoad()
/*for (index, element) in list.enumerated()*/
for (index, element) in cardsInHand.enumerated() {
let img = UIImage(named: "\(element)")
let imgView = UIImageView(image: img)
imgView.isUserInteractionEnabled = true
handScrollView.addSubview(imgView)
//add tap gesture recognizer
let tapRec = UITapGestureRecognizer(target: self, action: #selector(self.cardTapped))
imgView .addGestureRecognizer(tapRec)
imgView.frame = CGRect(x: 5 + (5 + WIDTH) * CGFloat(index), y: 5, width: WIDTH, height: HEIGHT)
}
//test at card tapped function
func cardTapped(){
handScrollView.setContentOffset(CGPoint(x: WIDTH, y: 0), animated: true)
}
到目前为止,它只是将 scrollView 上的偏移量设置为 WIDTH(即 110),无论点击哪张卡片,因为我不知道如何引用点击的 imgView。
最佳答案
如果您想要 imageView
的索引,请在循环中设置 imageView
的 tag
,然后简单地传递 的引用UITapGestureRecognizer
在您的方法 cardTapped
中。
for (index, element) in cardsInHand.enumerated() {
let img = UIImage(named: "\(element)")
let imgView = UIImageView(image: img)
imgView.isUserInteractionEnabled = true
handScrollView.addSubview(imgView)
//add tap gesture recognizer
let tapRec = UITapGestureRecognizer(target: self, action: #selector(self.cardTapped))
imgView.addGestureRecognizer(tapRec)
//Set tag of imageView
imgView.tag = index
imgView.frame = CGRect(x: 5 + (5 + WIDTH) * CGFloat(index), y: 5, width: WIDTH, height: HEIGHT)
}
//Now pass tapGesture reference in your method like this
func cardTapped(gesture: UITapGestureRecognizer) {
if let index = gesture.view?.tag {
handScrollView.setContentOffset(CGPoint(x: CGFloat(index) * WIDTH, y: 0), animated: true)
}
}
关于ios - setContentOffset 到 scrollView 中的 UIImage loaction,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40714032/