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


当前回答

Xamarin的。iOS版本的接受答案

var bottomOffset = new CGPoint (0,
     scrollView.ContentSize.Height - scrollView.Frame.Size.Height
     + scrollView.ContentInset.Bottom);

scrollView.SetContentOffset (bottomOffset, false);

其他回答

滚动到顶部

- CGPoint topOffset = CGPointMake(0, 0);
- [scrollView setContentOffset:topOffset animated:YES];

滚动到底部

- CGPoint bottomOffset = CGPointMake(0, scrollView.contentSize.height - self.scrollView.bounds.size.height);
 - [scrollView setContentOffset:bottomOffset animated:YES];

使用(可选)footerView和contentInset,解决方案是:

CGPoint bottomOffset = CGPointMake(0, _tableView.contentSize.height - tableView.frame.size.height + _tableView.contentInset.bottom);
if (bottomOffset.y > 0) [_tableView setContentOffset: bottomOffset animated: YES];

Xamarin的。iOS版本的接受答案

var bottomOffset = new CGPoint (0,
     scrollView.ContentSize.Height - scrollView.Frame.Size.Height
     + scrollView.ContentInset.Bottom);

scrollView.SetContentOffset (bottomOffset, false);

正如这里所解释的 https://janeshswift.com/ios/swift/how-to-scroll-to-a-position-programmatically-in-uiscrollview/

我们可以创建一个自定义UIScrollView扩展为

extension UIScrollView {
    
    func scrollToTop(animated: Bool = false) {
        setContentOffset(CGPoint(x: contentOffset.x, y: -adjustedContentInset.top), animated: animated)
    }
    
    var bottomContentOffsetY: CGFloat {
        max(contentSize.height - bounds.height + adjustedContentInset.bottom, -adjustedContentInset.top)
    }
    
    func scrollToBottom(animated: Bool = false) {
        setContentOffset(CGPoint(x: contentOffset.x, y: bottomContentOffsetY), animated: animated)
    }
    
    func scrollToLeading(animated: Bool = false) {
        setContentOffset(CGPoint(x: -adjustedContentInset.left, y: contentOffset.y), animated: animated)
    }
    
    var trailingContentOffsetX: CGFloat {
        max(contentSize.width - bounds.width + adjustedContentInset.right, -adjustedContentInset.left)
    }
    
    func scrollToTrailing(animated: Bool = false) {
        setContentOffset(CGPoint(x: trailingContentOffsetX, y: contentOffset.y), animated: animated)
    }
    
    func scrollViewToVisible(_ view: UIView, animated: Bool = false) {
        scrollRectToVisible(convert(view.bounds, from: view), animated: true)
    }
    
    var isOnTop: Bool {
        contentOffset.y <= -adjustedContentInset.top
    }
    
    var isOnBottom: Bool {
        contentOffset.y >= bottomContentOffsetY
    }
    
}

把它当作——

DispatchQueue.main.async {
    self.itemsScrollView.scrollToBottom()
}

将内容偏移设置为内容大小的高度是错误的:它将内容的底部滚动到滚动视图的顶部,因此看不到。

正确的解决方案是滚动内容的底部到滚动视图的底部,就像这样(sv是UIScrollView):

CGSize csz = sv.contentSize;
CGSize bsz = sv.bounds.size;
if (sv.contentOffset.y + bsz.height > csz.height) {
    [sv setContentOffset:CGPointMake(sv.contentOffset.x, 
                                     csz.height - bsz.height) 
                animated:YES];
}