我怎么能让一个UIScrollView滚动到我的代码底部?或者用更一般的方式,到子视图的任意点?


当前回答

如果你不需要动画,这是可行的:

[self.scrollView setContentOffset:CGPointMake(0, CGFLOAT_MAX) animated:NO];

其他回答

快速执行:

extension UIScrollView {
   func scrollToBottom(animated: Bool) {
     if self.contentSize.height < self.bounds.size.height { return }
     let bottomOffset = CGPoint(x: 0, y: self.contentSize.height - self.bounds.size.height)
     self.setContentOffset(bottomOffset, animated: animated)
  }
}

使用它:

yourScrollview.scrollToBottom(animated: true)

如果你以某种方式改变scrollView contentSize(例如,添加一些东西到stackView是在scrollView),你必须调用scrollView. layoutifneeded()在滚动之前,否则它什么都不做。

例子:

scrollView.layoutIfNeeded()
let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.size.height + scrollView.contentInset.bottom)
if(bottomOffset.y > 0) {
    scrollView.setContentOffset(bottomOffset, animated: true)
}

要滚动到底部,我们必须使用目标视图的最大高度。

import UIKit

extension UIScrollView {

    func scrollToBottomOf(targetView: UIView, animated: Bool) {
        setContentOffset(CGPoint(x:targetView.frame.minX, y:targetView.frame.maxY), animated: animated)
    }
}

//func invocation example 
optionScrollView.scrollToBottomOf(targetView: self.optionsStackView, animated: false)

Valdyr,希望这对你有帮助

CGPoint bottomOffset = CGPointMake(0, [textView contentSize].height - textView.frame.size.height);

if (bottomOffset.y > 0)
 [textView setContentOffset: bottomOffset animated: YES];

我发现contentSize并没有真正反映文本的实际大小,所以当尝试滚动到底部时,它会有点偏离。确定实际内容大小的最佳方法实际上是使用NSLayoutManager的usedRectForTextContainer:方法:

UITextView *textView;
CGSize textSize = [textView.layoutManager usedRectForTextContainer:textView.textContainer].size;

要确定在UITextView中实际显示了多少文本,可以通过从帧高度中减去文本容器嵌入来计算。

UITextView *textView;
UIEdgeInsets textInsets = textView.textContainerInset;
CGFloat textViewHeight = textView.frame.size.height - textInsets.top - textInsets.bottom;

然后就很容易滚动了:

// if you want scroll animation, use contentOffset
UITextView *textView;
textView.contentOffset = CGPointMake(textView.contentOffset.x, textSize - textViewHeight);

// if you don't want scroll animation
CGRect scrollBounds = textView.bounds;
scrollBounds.origin = CGPointMake(textView.contentOffset.x, textSize - textViewHeight);
textView.bounds = scrollBounds;

一些数字用于参考空UITextView的不同大小。

textView.frame.size = (width=246, height=50)
textSize = (width=10, height=16.701999999999998)
textView.contentSize = (width=246, height=33)
textView.textContainerInset = (top=8, left=0, bottom=8, right=0)