繁体   English   中英

选择滚动视图子视图时,在子视图位置滚动

[英]when select scroll view subview scroll at subview position

我想将子视图添加到滚动视图,有我的代码将子视图添加到滚动视图,我为子视图添加手势,并且我想当该子视图的任何子视图位于视图中心时。 怎么办呢?

        var startpoint = UIScreen.main.bounds.width / 4
        var with = 150
        var height = 55
        var space = 15

        override func viewDidLoad() {
                super.viewDidLoad()

                let max = 4
            scrollView.delegate = self
            let bound = self.view.bounds.width / 4

            for index in 0...max {

                catView = CategoryView.init(frame: CGRect(x: (with + space) * index + Int(startpoint) , y: 0, width: with, height: height))

                let label1 = UILabel(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
                catView.backgroundColor = #colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1)
                label1.text = String(index)
                label1.textColor = #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1)
                label1.textAlignment = .center
                catView.addSubview(label1)

                catView.tag = index

                self.allView.append(catView)

                self.scrollView.addSubview(catView)

     }

            let tapGestureRecognizer = UITapGestureRecognizer(target:self, action: #selector(self.subviewTapped(recognizer:)))
            scrollView.addGestureRecognizer(tapGestureRecognizer)
            scrollView.isUserInteractionEnabled = true

        self.scrollView.contentSize = CGSize(width:CGFloat(scrollView.subviews.count * 150) + CGFloat(bound) , height:self.scrollView.frame.height)

            }    
  func subviewTapped(recognizer : UIGestureRecognizer) {

        let tappedPoint: CGPoint = recognizer.location(in: self.scrollView!)
        let x: CGFloat = tappedPoint.x
        let y: CGFloat = tappedPoint.y

        print(tappedPoint)
        print(x)
        print(y)

        let index = Int(Int(x - startpoint) / with)
        self.label.text = String(index)
        var scrollRect = scrollView.subviews[index].frame
        scrollRect.origin.x = self.view.center.x
        let centerView = CGRect(x: Int(self.view.center.x), y: 0, width: 75, height: 55)
        scrollView.scrollRectToVisible(centerView, animated: true)
        scrollView.contentOffset = CGPoint(x: scrollRect.origin.x, y: 0)
    }

类似于Yandex.taxi应用程序

在此处输入图片说明

在您的代码示例中,您同时设置了

scrollView.scrollRectToVisible(centerView, animated: true)
scrollView.contentOffset = CGPoint(x: scrollRect.origin.x, y: 0)

您只需要调用scrollRectToVisible 但是,您可能想给centerView rect一个除0之外的y值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM