Программно прокрутите UIScrollView до вершины дочернего UIView (subview) в Swift
В моем UIScrollView есть несколько экранов для содержимого, которые только прокручиваются по вертикали.
Я хочу программно прокрутить список, содержащийся где-то в этой иерархии.
Перемещение UIScrollView так, чтобы дочерний вид находился в верхней части UIScrollView (либо анимированный, либо не)
Ответы
Ответ 1
Здесь расширение, которое я написал.
Использование:
Вызывается из моего viewController, self.scrollView - это выход в UIScrollView, а self.commentsHeader - это представление внутри него, внизу:
self.scrollView.scrollToView(self.commentsHeader, animated: true)
Код:
Вам нужен только метод scrollToView, но в методах scrollToBottom/ scrollToTop тоже, как вам, вероятно, понадобятся и эти, но чувствуйте чтобы удалить их.
extension UIScrollView {
// Scroll to a specific view so that it top is at the top our scrollview
func scrollToView(view:UIView, animated: Bool) {
if let origin = view.superview {
// Get the Y position of your child view
let childStartPoint = origin.convertPoint(view.frame.origin, toView: self)
// Scroll to a rectangle starting at the Y of your subview, with a height of the scrollview
self.scrollRectToVisible(CGRectMake(0, childStartPoint.y, 1, self.frame.height), animated: animated)
}
}
// Bonus: Scroll to top
func scrollToTop(animated: Bool) {
let topOffset = CGPoint(x: 0, y: -contentInset.top)
setContentOffset(topOffset, animated: animated)
}
// Bonus: Scroll to bottom
func scrollToBottom() {
let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height + contentInset.bottom)
if(bottomOffset.y > 0) {
setContentOffset(bottomOffset, animated: true)
}
}
}
Ответ 2
scrollView.scrollRectToVisible(CGRect(x: x, y: y, width: 1, height:
1), animated: true)
или
scrollView.setContentOffset(CGPoint(x: x, y: y), animated: true)
Другой способ -
scrollView.contentOffset = CGPointMake(x,y);
и я делаю это с таким анимированным
[UIView animateWithDuration:2.0f delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
scrollView.contentOffset = CGPointMake(x, y); }
completion:NULL];
Ответ 3
scrollView.setContentOffset(CGPoint, animated: Bool)
Где координата точки y является координатой y кадра представления, которую вы хотите показать относительно представления содержимого прокрутки.
Ответ 4
Вот мой ответ, это быстро. Это будет прокручивать страницы в scrollview бесконечно.
private func startBannerSlideShow()
{
UIView.animate(withDuration: 6, delay: 0.1, options: .allowUserInteraction, animations: {
scrollviewOutlt.contentOffset.x = (scrollviewOutlt.contentOffset.x == scrollviewOutlt.bounds.width*2) ? 0 : scrollviewOutlt.contentOffset.x+scrollviewOutlt.bounds.width
}, completion: { (status) in
self.startBannerSlideShow()
})
}
Ответ 5
Для прокрутки вверх или вниз с завершением анимации
// MARK: - UIScrollView extensions
extension UIScrollView {
/// Animate scroll to bottom with completion
///
/// - Parameters:
/// - duration: TimeInterval
/// - completion: Completion block
func animateScrollToBottom(withDuration duration: TimeInterval,
completion: (()->())? = nil) {
UIView.animate(withDuration: duration, animations: { [weak self] in
self?.setContentOffset(CGPoint.zero, animated: false)
}, completion: { finish in
if finish { completion?() }
})
}
/// Animate scroll to top with completion
///
/// - Parameters:
/// - duration: TimeInterval
/// - completion: Completion block
func animateScrollToBottomTop(withDuration duration: TimeInterval,
completion: (()->())? = nil) {
UIView.animate(withDuration: duration, animations: { [weak self] in
guard let `self` = self else {
return
}
let desiredOffset = CGPoint(x: 0, y: -self.contentInset.top)
self.setContentOffset(desiredOffset, animated: false)
}, completion: { finish in
if finish { completion?() }
})
}
}