当选择滚动视图子视图滚动到子视图位置时

时间:2017-02-27 13:43:42

标签: ios swift uiscrollview

我想将子视图添加到滚动视图,我的代码用于添加子视图以滚动视图,我为子视图添加手势,我想在任何子视图时此子视图位于视图中心。怎么办呢?

        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应用程序

enter image description here

1 个答案:

答案 0 :(得分:0)

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

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

您只需拨打scrollRectToVisible即可。但是,除了0之外,您可能希望为centerView rect提供y值。