1
votes

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
What have you tried? Post your Code. PS: By default, if you set the proper content size to ScrollView, it will scroll. - Venk
@ Venkat, thank you for your response, you can see my code above. - user2396625
why you are keeping scrollView in Middle? why dont you keep it to full screen? - Venk
That is the whole point, to practice the use of Gesture Recognizers and all. - user2396625
ok. In swipe gesture recognizer method, change the content offset of scrollview. - Venk

2 Answers

1
votes

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.

0
votes

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