2

I have attached an image here I am a newbie to iOS development. My question is as follows:

I want to swipe my scrollView outside of its width using gesture control. To be precise I want my UIScrollView to scroll when swipe is performed in the subview (there is only one subview).

I have gone through several StackOverflow question but I couldn't quite get a correct answer.

Your help is much appreciated!

class ViewController: UIViewController, UIGestureRecognizerDelegate {

@IBOutlet weak var scrollView: UIScrollView!

var images = [UIImageView]()
override func viewDidLoad() {
    super.viewDidLoad()
}

override func viewDidAppear(_ animated: Bool) {
    var contentWidth: CGFloat = 0.0
    for x in 0...2 {
        let image = UIImage(named: "icon\(x).png")
        let imageView = UIImageView(image:image)
        images.append(imageView)

        var newX: CGFloat = 0.0

        newX = scrollView.frame.size.width/2 + scrollView.frame.size.width * CGFloat(x)
        contentWidth += newX

        scrollView.addSubview(imageView)
        imageView.frame = CGRect(x: newX - 75, y: (scrollView.frame.size.height/2) - 75, width: 150, height: 150)

    }
    scrollView.clipsToBounds = false
    scrollView.contentSize = CGSize(width: contentWidth, height: view.frame.size.height)
}

As you can see in the image the width of my UIScrollView has a grey background color (I did that to illustrate my point). Now I want to also scroll the scroll view when a user swipes in the subview (non-grey) UIImageView.

I have added the following function and made a return of yes to enable both views to recognize gestures simultaneously. But, I am not getting the desired result. Can anyone take a look?

func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }

2 Answers2

2

Place view.addGestureRecognizer(scrollView.panGestureRecognizer) in viewDidLoad function.

What it eventually does is it assigns scrollview's gesture recognizer to look for gestures in main view. So it automatically move content of scrollview even when gestures are outside of the scrollview rect.

Pavan Jaju
  • 873
  • 11
  • 19
0

you can forward touch events in that subview to scrollview. see this answer

Community
  • 1
  • 1
Mohammadalijf
  • 1,387
  • 9
  • 19