2017-02-27 207 views
0

我想添加子視圖滾動視圖,有我的代碼添加子視圖滾動視圖,我爲子視圖添加手勢,並且我想當這個子視圖中找到任何子視圖視圖中心。怎麼做到這一點?當在子視圖位置選擇滾動視圖子視圖滾動

 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

+0

當'CategoryView'位於可見滾動視圖的中心時,您想要執行什麼操作? – dmorrow

+0

我想添加這個視圖時顯示另一個滾動視圖,我將添加圖像樣本。 – ava

+0

@dmorrow我正在編輯我的代碼,現在我可以在滾動視圖中找到選定的女巫視圖,但現在我想要點擊此子視圖滾動視圖滾動並選擇子視圖位於視圖中心。 – ava

回答

0

在你的代碼示例,您設置兩個

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

您應該只需要調用scrollRectToVisible。但是,您可能希望centerView正整數值爲y以外的值。

相關問題