簡體   English   中英

setContentOffset為scrollView中的UIImage位置

[英]setContentOffset to UIImage loaction in scrollView

我已經以編程方式將imageViews中的圖像添加到了一個for循環中的數組中5個對象的父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設置的tag是的imageView你的循環內,然后通過簡單的參考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) 
    }        
}

更改

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM