【问题标题】:setContentOffset to UIImage loaction in scrollViewsetContentOffset 到滚动视图中的 UIImage 位置
【发布时间】:2016-11-21 06:28:13
【问题描述】:

我以编程方式将 imageViews 中的图像添加到 for 循环中的父 scrollView 中,用于数组中的 5 个对象。每个 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。

【问题讨论】:

    标签: ios iphone swift uiscrollview uikit


    【解决方案1】:

    如果您想要imageView 的索引,请在循环内设置imageViewtag,然后只需在方法cardTapped 中传递UITapGestureRecognizer 的引用。

    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) 
        }        
    }
    

    【讨论】:

    • 谢谢!像魅力一样工作。
    • @Bezz 欢迎朋友 :)
    【解决方案2】:

    改变

    let tapRec = UITapGestureRecognizer(target: self, action: #selector(self.cardTapped))
    

    let tapRec = UITapGestureRecognizer(target: self, action: #selector(self.cardTapped(_:)))
    

    这将允许您将点击手势作为参数传递给您的函数,然后您可以访问应用它的视图-

    func cardTapped(_ sender: UITapGestureRecognizer) {
        print(sender.view?.center)
    }
    

    【讨论】:

      猜你喜欢
      • 2015-05-06
      • 2014-10-29
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 2013-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多