13.3 C
London
Wednesday, September 11, 2024

ios – In a UIScrollView with a lot of tappable picture views, what’s a great way to enhance efficiency?


It feels unusual that a number of faucet gestures would trigger you hurt however you will get away with a easy single gesture recogniser doing one thing like the next:

class ContainerView: UIView {
    
    @IBOutlet personal var scrollView: UIScrollView?
    @IBOutlet personal var imageViews: [UIImageView]?
    
    personal func attachTapGestureRecogniser() {
        addGestureRecognizer(UITapGestureRecognizer(goal: self, motion: #selector(onImageTapped)))
    }
    
    @objc personal func onImageTapped(_ sender: UIGestureRecognizer) {
        guard let tappedImageIndex = imageViews?.firstIndex(the place: { $0.bounds.accommodates(sender.location(in: $0)) }) else {
            // No picture was tapped
            return
        }
        print("Picture at index (tappedImageIndex) was tapped")
    }
    
}

If pictures are overlapping and firstIndex is just not applicable then you possibly can nonetheless get all of the picture views throughout the hit space and course of them higher.

Alternatively when you have extra data you would compute the index probably like so:

@objc personal func onImageTapped2(_ sender: UIGestureRecognizer) {
    let rowHeight = 200 // Depends upon your grid structure
    let columnWidth = 200 // Depends upon your grid structure
    let itemsPerRow = 3
    
    let positionInScrollView = sender.location(in: scrollView)
    
    let row = Int(positionInScrollView.y/CGFloat(rowHeight))
    let column = Int(positionInScrollView.x/CGFloat(columnWidth))
    
    let tappedImageIndex = row*itemsPerRow + column
    
    guard tappedImageIndex < imageViews?.rely ?? 0 else {
        // No picture was tapped
        return
    }
    print("Picture at index (tappedImageIndex) was tapped")
}

If required you possibly can go into deeper ranges utilizing instruments like the next:

override func touchesBegan(_ touches: Set<UITouch>, with occasion: UIEvent?) {
    guard let pressLocation = touches.first?.location(in: self) else { return }
    let locationInScrollView = self.convert(pressLocation, to: scrollView)
    // Do stuff right here with
}

Latest news
Related news

LEAVE A REPLY

Please enter your comment!
Please enter your name here