【问题标题】:using gesture recognizer on a subview of UIScrollView - Swift在 UIScrollView 的子视图上使用手势识别器 - Swift
【发布时间】:2017-04-21 22:39:43
【问题描述】:

I have attached an image here 我是iOS 开发的新手。我的问题如下:

我想使用手势控制将我的scrollView 滑动到其宽度之外。 准确地说,我希望我的UIScrollViewsubview 中执行滑动时滚动(只有一个subview)。

我已经解决了几个 StackOverflow 问题,但我无法得到正确答案。

非常感谢您的帮助!

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

正如您在图像中看到的那样,我的 UIScrollView 的宽度具有灰色背景色(我这样做是为了说明我的观点)。现在,当用户在子视图(非灰色)UIImageView 中滑动时,我还想滚动滚动视图。

我添加了以下函数并返回 yes 以使两个视图同时识别手势。但是,我没有得到想要的结果。有人可以看看吗?

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

【问题讨论】:

  • 你试过什么?发布您的代码。 PS:默认情况下,如果你给ScrollView设置合适的内容大小,它会滚动。
  • @Venkat,谢谢你的回复,上面可以看到我的代码。
  • 为什么要将 scrollView 保留在中间?为什么不让它全屏显示?
  • 这就是重点,练习使用手势识别器等等。
  • 好的。在滑动手势识别器方法中,更改滚动视图的内容偏移量。

标签: ios uiscrollview swift3


【解决方案1】:

view.addGestureRecognizer(scrollView.panGestureRecognizer) 放入viewDidLoad 函数中。

它最终所做的是分配滚动视图的手势识别器以在主视图中查找手势。因此,即使手势在滚动视图矩形之外,它也会自动移动滚动视图的内容。

【讨论】:

    【解决方案2】:

    您可以将该子视图中的触摸事件转发到滚动视图。看到这个answer

    【讨论】:

    • 感谢您的回复,我会研究解决方案,看看我会得到什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-29
    • 2013-03-14
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多