在Subview位置选择滚动视图子视图滚动
Posted
技术标签:
【中文标题】在Subview位置选择滚动视图子视图滚动【英文标题】:when select scroll view subview scroll at subview position 【发布时间】:2017-02-27 13:43:41 【问题描述】:我想将子视图添加到滚动视图,有我的代码用于将子视图添加到滚动视图,我正在为子视图添加手势,并且我想当任何子视图位于视图中心时。怎么会这样?
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 应用程序
【问题讨论】:
当CategoryView
位于可见滚动视图的中心时你想做什么?
我想在添加此视图时在此顶部显示另一个滚动视图,我将添加图像示例。
@dmorrow 我正在编辑我的代码,现在我可以找到在滚动视图中选择的女巫视图,但现在我想在点击此子视图时滚动视图滚动并且选定的子视图位于视图中心。跨度>
【参考方案1】:
在您的代码示例中,您同时设置了两者
scrollView.scrollRectToVisible(centerView, animated: true)
scrollView.contentOffset = CGPoint(x: scrollRect.origin.x, y: 0)
您只需致电scrollRectToVisible
。但是,您可能希望为您的 centerView
rect 提供一个除 0 之外的 y
值。
【讨论】:
以上是关于在Subview位置选择滚动视图子视图滚动的主要内容,如果未能解决你的问题,请参考以下文章
UITableViewCell 滚动时复制 UITextfield 子视图
以编程方式将 UIScrollView 滚动到 Swift 中的子 UIView(子视图)的顶部