How to make infinity scroll on Scroll View in Xcode project? - ios

I have a Scrollview in my app that shows a few slides,
the default behaviour of the slides are when you reach the last one (ie slide 5 for example) is that it doesn't scroll more to the right,
or when you go to the first one it doesn't scroll more to the left.
how do I make it infinity loop , meaning when I see the last slide, and I scroll more right, it will just scroll to the first one?
(or from the first one left it will scroll to the last one)
here is my scrollViewDidScroll:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let pageIndex = round(scrollView.contentOffset.x/view.frame.width)
pageControl.currentPage = Int(pageIndex)
let maximumHorizontalOffset: CGFloat = scrollView.contentSize.width - scrollView.frame.width
let currentHorizontalOffset: CGFloat = scrollView.contentOffset.x
// vertical
let maximumVerticalOffset: CGFloat = scrollView.contentSize.height - scrollView.frame.height
let currentVerticalOffset: CGFloat = scrollView.contentOffset.y
let percentageHorizontalOffset: CGFloat = currentHorizontalOffset / maximumHorizontalOffset
let percentageVerticalOffset: CGFloat = currentVerticalOffset / maximumVerticalOffset
/*
* below code changes the background color of view on paging the scrollview
*/
// self.scrollView(scrollView, didScrollToPercentageOffset: percentageHorizontalOffset)
/*
* below code scales the imageview on paging the scrollview
*/
let percentOffset: CGPoint = CGPoint(x: percentageHorizontalOffset, y: percentageVerticalOffset)
print ("present offset: ", percentOffset.x)
if(percentOffset.x > 0 && percentOffset.x <= 0.25) {
slides[0].mainPic.transform = CGAffineTransform(scaleX: (0.25-percentOffset.x)/0.25, y: (0.25-percentOffset.x)/0.25)
slides[1].mainPic.transform = CGAffineTransform(scaleX: percentOffset.x/0.25, y: percentOffset.x/0.25)
} else if(percentOffset.x > 0.25 && percentOffset.x <= 0.50) {
slides[1].mainPic.transform = CGAffineTransform(scaleX: (0.50-percentOffset.x)/0.25, y: (0.50-percentOffset.x)/0.25)
slides[2].mainPic.transform = CGAffineTransform(scaleX: percentOffset.x/0.50, y: percentOffset.x/0.50)
} else if(percentOffset.x > 0.50 && percentOffset.x <= 0.75) {
slides[2].mainPic.transform = CGAffineTransform(scaleX: (0.75-percentOffset.x)/0.25, y: (0.75-percentOffset.x)/0.25)
slides[3].mainPic.transform = CGAffineTransform(scaleX: percentOffset.x/0.75, y: percentOffset.x/0.75)
} else if(percentOffset.x > 0.75 && percentOffset.x <= 1) {
slides[3].mainPic.transform = CGAffineTransform(scaleX: (1-percentOffset.x)/0.25, y: (1-percentOffset.x)/0.25)
slides[4].mainPic.transform = CGAffineTransform(scaleX: percentOffset.x, y: percentOffset.x)
}
}

Not sure about your current implementation but your solution will be something like, I'm assuming your slides array contains UIView for each slide. Change the code according to your current implementation.
(void)scrollViewDidScroll:(UIScrollView *)scrollView {
if(if(scrollView.contentOffset.x < 0)) {
CGPoint newOffset = CGPointMake(scrollView.bounds.size.width+scrollView.contentOffset.x, scrollView.contentOffset.y);
[scrollView setContentOffset:newOffset];
[self rotateViewsRight];
}
else if(scrollView.contentOffset.x > scrollView.bounds.size.width*2) {
CGPoint newOffset = CGPointMake(scrollView.contentOffset.x-scrollView.bounds.size.width, scrollView.contentOffset.y);
[scrollView setContentOffset:newOffset];
[self rotateViewsLeft];
}
}
-(void)rotateViewsRight {
UIView *endView = [slides lastObject];
[slides removeLastObject];
[slides insertObject:endView atIndex:0];
[self setContentViewFrames];
}
-(void)rotateViewsLeft {
UIView *endView = slides[0];
[slides removeObjectAtIndex:0];
[slides addObject:endView];
[self setContentViewFrames];
}
-(void) setContentViewFrames {
for(int i = 0; i < 5; i++) {
UIView * view = slides[i];
[view setFrame:CGRectMake(self.view.bounds.size.width*i, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
}
}

Related

How do i move the UILabel Depending on UISlider

How do I change the origin y of the UILabel depending on UISlider?
If the slider value is more than 1.5 labels, it should move back to its position or move down. I want to change the y origin depending on the scroll of UISlider value.
Until now I have tried this but it's not effective.
The below function is valueChanged method of UISlider:
internal func valueChanged(value: Float) {
if value > 1.0 && value < 1.5 {
let view = self.viewWithTag(400) as ! UIImageView
view.transform = CGAffineTransformScale(CGAffineTransformIdentity, CGFloat(value - 0.5), CGFloat(value - 0.5))
let label = self.viewWithTag(500) as ! UILabel
if value > lastValue {
label.frame.origin.y = (label.frame.origin.y + CGFloat(value - 0.5))
}
if value < lastValue {
label.frame.origin.y = (label.frame.origin.y - CGFloat(value - 0.5))
}
} else {
UIView.animateWithDuration(0.1) {
let view = self.viewWithTag(400) as ! UIImageView
view.transform = CGAffineTransformScale(CGAffineTransformIdentity, CGFloat(1.0), CGFloat(1.0))
}
}
}
I know it's a wrong approach.

How to restrict shifting of a pinch zoomed image to the image borders?

I set up a scrollView in storyboard with a single imageView using auto layout as shown here.
In addition I enabled pinch zooming for this imageView as described in the docs.
The imageView has 4 constraints of 0 to the sides of the scollView, and it has equal width and height to the main view, which has the scrollView as subview.
The imageView has aspectFit scaling mode, so in the unzoomed state, the image will extend fully from left to right, or from top to bottom (or both).
In the following example, it extends from top to bottom, leaving some background visible left and right:
I can pinch zoom the image so that it is larger than the screen:
I can shift the zoomed image up or down, but the movement stops before the background becomes visible on top or bottom. This is want I want.
However, I can shift the zoomed image left or right so that the background can be seen:
How can I avoid shifting the image so far (here, to the right). Like with top or bottom, it should stop moving at the border, so that no background becomes visible.
Not ideal solution but I hope it will help:
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale {
[self adjustScrollViewInsets];
}
- (void)adjustScrollViewInsets {
CGFloat imageWidth = self.imageView.image.size.width;
CGFloat imageHeight = self.imageView.image.size.height;
CGFloat aspect = imageWidth / imageHeight;
CGSize imageViewSize = self.imageView.frame.size;
if (imageViewSize.width / aspect <= imageViewSize.height) {
[self adjustVerticalInsetsWithImageHeight:(imageViewSize.width / aspect)];
} else {
[self adjustHorizontalInsetsWithImageWidth:(imageViewSize.height * aspect)];
}
}
- (void)adjustHorizontalInsetsWithImageWidth:(CGFloat)width {
CGFloat horizontalInset = (self.scrollView.contentSize.width - width) / 2;
if (width < self.scrollView.frame.size.width) {
horizontalInset = horizontalInset - (self.scrollView.frame.size.width - width) / 2;
}
[self.scrollView setContentInset:UIEdgeInsetsMake(0, -horizontalInset, 0, -horizontalInset)];
}
- (void)adjustVerticalInsetsWithImageHeight:(CGFloat)height {
CGFloat verticalInset = (self.scrollView.contentSize.height - height) / 2;
if (height < self.scrollView.frame.size.height) {
verticalInset = verticalInset - (self.scrollView.frame.size.height - height) / 2;
}
[self.scrollView setContentInset:UIEdgeInsetsMake(-verticalInset, 0, -verticalInset, 0)];
}
If you have troubles, check out this repo.
I was having the same problem and implemented in Swift 4.0 as given below and it worked for me.
Swift 4.0:
func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
adjustScrollViewInsets()
}
func adjustScrollViewInsets() {
let imageWidth = self.imageView.image?.size.width
let imageHeight = self.imageView.image?.size.height
let aspect = imageWidth! / imageHeight!
let imageViewSize = self.imageView.frame.size
if imageViewSize.width / aspect <= imageViewSize.height {
adjustVerticalInsetsWithImageHeight(height: imageViewSize.width / 2)
} else {
adjustHorizontalInsetsWithImageWidth(width: imageViewSize.height / 2)
}
}
func adjustHorizontalInsetsWithImageWidth(width: CGFloat) {
var horizontalInset = (self.scrollView.contentSize.width - width) / 2
if width < self.scrollView.contentSize.width {
horizontalInset = horizontalInset - (self.scrollView.frame.size.width - width) / 2
}
self.scrollView.contentInset = UIEdgeInsetsMake(0, -horizontalInset, 0, -horizontalInset)
}
func adjustVerticalInsetsWithImageHeight(height: CGFloat) {
var verticalInset = (self.scrollView.contentSize.height - height) / 2
if height < self.scrollView.frame.size.height {
verticalInset = verticalInset - (self.scrollView.frame.size.height - height) / 2
}
self.scrollView.contentInset = UIEdgeInsetsMake(-verticalInset, 0, -verticalInset, 0)
}

How to disable manually diagonal scrolling WHILE enable diagonal setContentOffset scroll annimation

I am using a collection view.
Although the directionLockEnabled can be set to YES, diagonal scrolling is still enabled.
So I found a solution somewhere:
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
self.offset = self.collectionView.contentOffset;
}
// control scroll to only horizontal & vertical
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGFloat deltaX = ABS(self.offset.x - self.collectionView.contentOffset.x);
CGFloat deltaY = ABS(self.offset.y - self.collectionView.contentOffset.y);
if (deltaX != 0 && deltaY != 0) {
if (deltaX >= deltaY) {
self.collectionView.contentOffset = CGPointMake(self.collectionView.contentOffset.x, self.offset.y);
}
else {
self.collectionView.contentOffset = CGPointMake(self.offset.x, self.collectionView.contentOffset.y);
}
}
}
However the side effect is when I call with x, y > 0
[self.collectionView setContentOffset:CGPointMake(x, y) animated:animated];
It doesn't scroll at all, because of the code block above.
How to deal with this?
To disable manually diagonal scrolling in Swift:
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
self.offset = scrollView.contentOffset
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let deltaX = abs(self.offset.x - self.collectionView.contentOffset.x)
let deltaY = abs(self.offset.y - self.collectionView.contentOffset.y)
if deltaX != 0 && deltaY != 0 {
if deltaX >= deltaY {
self.collectionView.contentOffset = CGPoint(x: self.collectionView.contentOffset.x, y: self.offset.y)
} else {
self.collectionView.contentOffset = CGPoint(x: self.offset.x, y: self.collectionView.contentOffset.y)
}
}
}
OK I figure it out...
scrollView.dragging can differentiate manual scrolling or auto scrolling...
You can do
collectionView.isScrollEnabled = false
It will disable a user from scrolling, but you will be able to scroll programmatically using
collectionView.scrollToItem(at:at:animated:)

Move a view when scrolling in UITableView

I have a UIView with a UITableView below it:
What I would like to do is to have the view above the UITableView move up (out of the way) when the user starts scrolling in the table in order to have more space for the UITableView (and come down when you scroll down again).
I know that this is normally done with a table header view, but my problem is that my table view is inside a tab (actually it is a side-scrolling page view implemented using TTSliddingPageviewcontroller). So while I only have one top UIView there are three UITableViews.
Is it possible to accomplish this manually? My first thought is to put everything in a UIScrollView, but according to Apple's documentation one should never place a UITableView inside a UIScrollView as this leads to unpredictable behavior.
Solution for Swift (Works perfectly with bounce enabled for scroll view):
var oldContentOffset = CGPointZero
let topConstraintRange = (CGFloat(120)..<CGFloat(300))
func scrollViewDidScroll(scrollView: UIScrollView) {
let delta = scrollView.contentOffset.y - oldContentOffset.y
//we compress the top view
if delta > 0 && topConstraint.constant > topConstraintRange.start && scrollView.contentOffset.y > 0 {
topConstraint.constant -= delta
scrollView.contentOffset.y -= delta
}
//we expand the top view
if delta < 0 && topConstraint.constant < topConstraintRange.end && scrollView.contentOffset.y < 0{
topConstraint.constant -= delta
scrollView.contentOffset.y -= delta
}
oldContentOffset = scrollView.contentOffset
}
Since UITableView is a subclass of UIScrollView, your table view's delegate can receive UIScrollViewDelegate methods.
In your table view's delegate:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
static CGFloat previousOffset;
CGRect rect = self.view.frame;
rect.origin.y += previousOffset - scrollView.contentOffset.y;
previousOffset = scrollView.contentOffset.y;
self.view.frame = rect;
}
More simple and fast approach
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGRect rect = self.view.frame;
rect.origin.y = -scrollView.contentOffset.y;
self.view.frame = rect;
}
Swift 3 & 4:
var oldContentOffset = CGPoint.zero
let topConstraintRange = (CGFloat(0)..<CGFloat(140))
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let delta = scrollView.contentOffset.y - oldContentOffset.y
//we compress the top view
if delta > 0 && yourConstraint.constant > topConstraintRange.lowerBound && scrollView.contentOffset.y > 0 {
yourConstraint.constant -= delta
scrollView.contentOffset.y -= delta
}
//we expand the top view
if delta < 0 && yourConstraint.constant < topConstraintRange.upperBound && scrollView.contentOffset.y < 0{
yourConstraint.constant -= delta
scrollView.contentOffset.y -= delta
}
oldContentOffset = scrollView.contentOffset
}
I added some constraints to the last solution to prevent some strange behaviours in case of fast scrolling
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let delta = scrollView.contentOffset.y - oldContentOffset.y
//we compress the top view
if delta > 0 && topConstraint.constant > topConstraintRange.lowerBound && scrollView.contentOffset.y > 0 {
searchHeaderTopConstraint.constant = max(topConstraintRange.lowerBound, topConstraint.constant - delta)
scrollView.contentOffset.y -= delta
}
//we expand the top view
if delta < 0 && topConstraint.constant < topConstraintRange.upperBound && scrollView.contentOffset.y < 0 {
topConstraint.constant = min(searchHeaderTopConstraint.constant - delta, topConstraintRange.upperBound)
scrollView.contentOffset.y -= delta
}
oldContentOffset = scrollView.contentOffset
}
Someone asked for the code for my solution so I am posting it here as an answer. The credit for the idea should still go to NobodyNada.
In my UITableViewController I implement this delegate method:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
[[NSNotificationCenter defaultCenter] postNotificationName:#"TableViewScrolled" object:nil userInfo:scrollUserInfo];
}
scrollUserInfo is a NSDictionary where I put my UITableView to pass it with the notification (I do this in viewDidLoad so I only have to do it once):
scrollUserInfo = [NSDictionary dictionaryWithObject:self.tableView forKey:#"scrollView"];
Now, in the view controller that has the view I want to move off screen while scrolling I do this in viewDidLoad:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(handleScroll:) name:#"TableViewScrolled" object:nil];
And finally I have the method:
- (void)handleScroll:(NSNotification *)notification {
UIScrollView *scrollView = [notification.userInfo valueForKey:#"scrollView"];
CGFloat currentOffset = scrollView.contentOffset.y;
CGFloat height = scrollView.frame.size.height;
CGFloat distanceFromBottom = scrollView.contentSize.height - currentOffset;
if (previousOffset < currentOffset && distanceFromBottom > height) {
if (currentOffset > viewHeight)
currentOffset = viewHeight;
self.topVerticalConstraint.constant += previousOffset - currentOffset;
previousOffset = currentOffset;
}
else {
if (previousOffset > currentOffset) {
if (currentOffset < 0)
currentOffset = 0;
self.topVerticalConstraint.constant += previousOffset - currentOffset;
previousOffset = currentOffset;
}
}
}
previousOffset is an instance variable CGFloat previousOffset;.
topVerticalConstraint is a NSLayoutConstraint that is set as a IBOutlet. It goes from the top of the view to the top of its superview and the initial value is 0.
It's not perfect. For instance, if the user scrolls very aggressively up the movement of the view can get a bit jerky. The issue is worse for large views; if the view is small enough there is no problem.
To create like this animation,
lazy var redView: UIView = {
let view = UIView(frame: CGRect(x: 0, y: 0, width:
self.view.frame.width, height: 100))
view.backgroundColor = .red
return view
}()
var pageMenu: CAPSPageMenu?
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(redView)
let rect = CGRect(x: 0, y: self.redView.frame.maxY, width: self.view.bounds.size.width, height:(self.view.bounds.size.height - (self.redView.frame.maxY)))
pageMenu?.view.frame = rect
self.view.addSubview(pageMenu!.view)
}
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offset = scrollView.contentOffset.y
if(offset > 100){
self.redView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: 0)
}else{
self.redView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: 100 - offset)
}
let rect = CGRect(x: 0, y: self.redView.frame.maxY, width: self.view.bounds.size.width, height:(self.view.bounds.size.height - (self.redView.frame.maxY)))
pageMenu?.view.frame = rect
}
you must change pageMenu.view with your collectionView/tableView
I know this post in very old. I tried above solutions but neither worked for me for tried my own, hopefully it can help you. This scenario is pretty common, as apple suggested not to use TableViewController inside any ScrollView because the compiler will confused as in whom to respond becuase it will be getting two delegate call back - one from ScrollViewDelegate and another from UITableViewDelegate.
Instead we can use ScrollViewDelegate and disable the UITableViewScrolling.
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGFloat currentOffSetY = scrollView.contentOffset.y;
CGFloat diffOffset = self.lastContentOffset - currentOffSetY;
self.scrollView.contentSize = CGSizeMake(self.scrollView.contentSize.width, 400 + [self.tableView contentSize].height);
if (self.lastContentOffset < scrollView.contentOffset.y) {
tableView.frame = CGRectMake(tableView.frame.origin.x, tableView.frame.origin.y , tableView.frame.size.width, tableView.size.height - diffOffset);
}
if (self.lastContentOffset > scrollView.contentOffset.y) {
tableView.frame = CGRectMake(tableView.frame.origin.x, tableViewframe.origin.y, tableViewframe.size.width, tableView.frame.size.height + diffOffset);
}
self.lastContentOffset = currentOffSetY;
}
Here lastContentOffset is CGFloat defined as property
The View Heirarchy is as follows:
ViewController --> View contains ScrollView (whose delegate method is defined above) --> Contain TableView.
By the above code we are manually increasing and decreasing the height of the table view along with the content size of ScrollView.
Remember to disable the Scrolling of TableView.
You can make it like this:
Add these as your class variables:
private let NUMBER_OF_ROWS: Int = 256
private let ROW_HEIGHT: CGFloat = 75.0
private let MINIMUM_CONSTANT_VALUE: CGFloat = -150.0 /// This is the hidable view's height
#IBOutlet weak var hidableViewTopConstraint: NSLayoutConstraint! /// This is an outlet from your storyboard
private var lastContentOffset: CGFloat = 0.0
This goes on your viewDidLoad():
tableView.delegate = self
And then you add this as an extension for your view controller:
extension ViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let delta = tableView.contentOffset.y - lastContentOffset
let canScrollUp: Bool =
delta < 0 &&
hidableViewTopConstraint.constant < 0 &&
scrollView.contentOffset.y < 0
let canScrollDown: Bool =
delta > 0 &&
hidableViewTopConstraint.constant > MINIMUM_CONSTANT_VALUE &&
tableView.contentOffset.y > 0
if canScrollUp || canScrollDown{
hidableViewTopConstraint.constant -= delta
tableView.contentOffset.y -= delta
}
lastContentOffset = tableView.contentOffset.y
}
}
But note that the scroll mechanism will only work when the TableView is scrolled. The top view wont collapse or expand if you scroll it.
I made an example project you can check, it is called iOSFixedHeaderList

UIScrollView scroll to bottom programmatically

How can I make a UIScrollView scroll to the bottom within my code? Or in a more generic way, to any point of a subview?
You can use the UIScrollView's setContentOffset:animated: function to scroll to any part of the content view. Here's some code that would scroll to the bottom, assuming your scrollView is self.scrollView:
Objective-C:
CGPoint bottomOffset = CGPointMake(0, self.scrollView.contentSize.height - self.scrollView.bounds.size.height + self.scrollView.contentInset.bottom);
[self.scrollView setContentOffset:bottomOffset animated:YES];
Swift:
let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.height + scrollView.contentInset.bottom)
scrollView.setContentOffset(bottomOffset, animated: true)
Swift version of the accepted answer for easy copy pasting:
let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.size.height)
scrollView.setContentOffset(bottomOffset, animated: true)
Simplest Solution:
[scrollview scrollRectToVisible:CGRectMake(scrollview.contentSize.width - 1,scrollview.contentSize.height - 1, 1, 1) animated:YES];
A swifty implementation:
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)
}
}
use it:
yourScrollview.scrollToBottom(animated: true)
Just an enhancement to the existing answer.
CGPoint bottomOffset = CGPointMake(0, self.scrollView.contentSize.height - self.scrollView.bounds.size.height + self.scrollView.contentInset.bottom);
[self.scrollView setContentOffset:bottomOffset animated:YES];
It takes care of the bottom inset as well (in case you're using that to adjust your scroll view when the keyboard is visible)
Setting the content offset to the height of the content size is wrong: it scrolls the bottom of the content to the top of the scroll view, and thus out of sight.
The correct solution is to scroll the bottom of the content to the bottom of the scroll view, like this (sv is the 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];
}
A Swift 2.2 solution, taking contentInset into account
let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.size.height + scrollView.contentInset.bottom)
scrollView.setContentOffset(bottomOffset, animated: true)
This should be in an extension
extension UIScrollView {
func scrollToBottom() {
let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height + contentInset.bottom)
setContentOffset(bottomOffset, animated: true)
}
}
Note that you may want to check if bottomOffset.y > 0 before scroll
What if contentSize is lower than bounds?
For Swift it is:
scrollView.setContentOffset(CGPointMake(0, max(scrollView.contentSize.height - scrollView.bounds.size.height, 0) ), animated: true)
Scroll To Top
- CGPoint topOffset = CGPointMake(0, 0);
- [scrollView setContentOffset:topOffset animated:YES];
Scroll To Bottom
- CGPoint bottomOffset = CGPointMake(0, scrollView.contentSize.height - self.scrollView.bounds.size.height);
- [scrollView setContentOffset:bottomOffset animated:YES];
It looks like all of the answers here didn't take the safe area into consideration.
Since iOS 11, iPhone X had a safe area introduced. This may affect the scrollView's contentInset.
For iOS 11 and above, to properly scroll to the bottom with the content inset included. You should use adjustedContentInset instead of contentInset. Check this code:
Swift:
let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.height + scrollView.adjustedContentInset.bottom)
scrollView.setContentOffset(bottomOffset, animated: true)
Objective-C
CGPoint bottomOffset = CGPointMake(0, self.scrollView.contentSize.height - self.scrollView.bounds.size.height + self.scrollView.adjustedContentInset.bottom);
[self.scrollView setContentOffset:bottomOffset animated:YES];
Swift extension (this keeps the original contentOffset.x):
extension UIScrollView {
func scrollsToBottom(animated: Bool) {
let bottomOffset = CGPoint(x: contentOffset.x,
y: contentSize.height - bounds.height + adjustedContentInset.bottom)
setContentOffset(bottomOffset, animated: animated)
}
}
References:
adjustedContentInset
I also found another useful way of doing this in the case you are using a UITableview (which is a subclass of UIScrollView):
[(UITableView *)self.view scrollToRowAtIndexPath:scrollIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
Using UIScrollView's setContentOffset:animated: function to scroll to the bottom in Swift.
let bottomOffset : CGPoint = CGPointMake(0, scrollView.contentSize.height - scrollView.bounds.size.height + scrollView.contentInset.bottom)
scrollView.setContentOffset(bottomOffset, animated: true)
If you somehow change scrollView contentSize (ex. add something to stackView which is inside scrollView) you must call scrollView.layoutIfNeeded() before scrolling, otherwise it does nothing.
Example:
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)
}
With an (optional) footerView and contentInset, the solution is:
CGPoint bottomOffset = CGPointMake(0, _tableView.contentSize.height - tableView.frame.size.height + _tableView.contentInset.bottom);
if (bottomOffset.y > 0) [_tableView setContentOffset: bottomOffset animated: YES];
Swift:
You could use an extension like this:
extension UIScrollView {
func scrollsToBottom(animated: Bool) {
let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height)
setContentOffset(bottomOffset, animated: animated)
}
}
Use:
scrollView.scrollsToBottom(animated: true)
valdyr, hope this will help you:
CGPoint bottomOffset = CGPointMake(0, [textView contentSize].height - textView.frame.size.height);
if (bottomOffset.y > 0)
[textView setContentOffset: bottomOffset animated: YES];
Category to the rescue!
Add this to a shared utility header somewhere:
#interface UIScrollView (ScrollToBottom)
- (void)scrollToBottomAnimated:(BOOL)animated;
#end
And then to that utility implementation:
#implementation UIScrollView(ScrollToBottom)
- (void)scrollToBottomAnimated:(BOOL)animated
{
CGPoint bottomOffset = CGPointMake(0, self.contentSize.height - self.bounds.size.height);
[self setContentOffset:bottomOffset animated:animated];
}
#end
Then Implement it wherever you like, for instance:
[[myWebView scrollView] scrollToBottomAnimated:YES];
For Horizontal ScrollView
If you like me has a Horizontal ScrollView and want to scroll to end of it (in my case to most right of it), you need to change some parts of the accepted answer:
Objective-C
CGPoint rightOffset = CGPointMake(self.scrollView.contentSize.width - self.scrollView.bounds.size.width + self.scrollView.contentInset.right, 0 );
[self.scrollView setContentOffset:rightOffset animated:YES];
Swift
let rightOffset: CGPoint = CGPoint(x: self.scrollView.contentSize.width - self.scrollView.bounds.size.width + self.scrollView.contentInset.right, y: 0)
self.scrollView.setContentOffset(rightOffset, animated: true)
A good way to ensure the bottom of your content is visible is to use the formula:
contentOffsetY = MIN(0, contentHeight - boundsHeight)
This ensures the bottom edge of your content is always at or above the bottom edge of the view. The MIN(0, ...) is required because UITableView (and probably UIScrollView) ensures contentOffsetY >= 0 when the user tries to scroll by visibly snapping contentOffsetY = 0. This looks pretty weird to the user.
The code to implement this is:
UIScrollView scrollView = ...;
CGSize contentSize = scrollView.contentSize;
CGSize boundsSize = scrollView.bounds.size;
if (contentSize.height > boundsSize.height)
{
CGPoint contentOffset = scrollView.contentOffset;
contentOffset.y = contentSize.height - boundsSize.height;
[scrollView setContentOffset:contentOffset animated:YES];
}
If you don't need animation, this works:
[self.scrollView setContentOffset:CGPointMake(0, CGFLOAT_MAX) animated:NO];
While Matt solution seems correct to me you need to take in account also the collection view inset if there is one that has been set-up.
The adapted code will be:
CGSize csz = sv.contentSize;
CGSize bsz = sv.bounds.size;
NSInteger bottomInset = sv.contentInset.bottom;
if (sv.contentOffset.y + bsz.height + bottomInset > csz.height) {
[sv setContentOffset:CGPointMake(sv.contentOffset.x,
csz.height - bsz.height + bottomInset)
animated:YES];
}
In swift:
if self.mainScroll.contentSize.height > self.mainScroll.bounds.size.height {
let bottomOffset = CGPointMake(0, self.mainScroll.contentSize.height - self.mainScroll.bounds.size.height);
self.mainScroll.setContentOffset(bottomOffset, animated: true)
}
Solution to scroll to last item of a table View :
Swift 3 :
if self.items.count > 0 {
self.tableView.scrollToRow(at: IndexPath.init(row: self.items.count - 1, section: 0), at: UITableViewScrollPosition.bottom, animated: true)
}
Didn't work for me, when I tried to use it in UITableViewController on self.tableView (iOS 4.1), after adding footerView. It scrolls out of the borders, showing black screen.
Alternative solution:
CGFloat height = self.tableView.contentSize.height;
[self.tableView setTableFooterView: myFooterView];
[self.tableView reloadData];
CGFloat delta = self.tableView.contentSize.height - height;
CGPoint offset = [self.tableView contentOffset];
offset.y += delta;
[self.tableView setContentOffset: offset animated: YES];
CGFloat yOffset = scrollView.contentOffset.y;
CGFloat height = scrollView.frame.size.height;
CGFloat contentHeight = scrollView.contentSize.height;
CGFloat distance = (contentHeight - height) - yOffset;
if(distance < 0)
{
return ;
}
CGPoint offset = scrollView.contentOffset;
offset.y += distance;
[scrollView setContentOffset:offset animated:YES];
I found that contentSize doesn't really reflect the actual size of the text, so when trying to scroll to the bottom, it will be a little bit off. The best way to determine the actual content size is actually to use the NSLayoutManager's usedRectForTextContainer: method:
UITextView *textView;
CGSize textSize = [textView.layoutManager usedRectForTextContainer:textView.textContainer].size;
To determine how much text actually is shown in the UITextView, you can calculate it by subtracting the text container insets from the frame height.
UITextView *textView;
UIEdgeInsets textInsets = textView.textContainerInset;
CGFloat textViewHeight = textView.frame.size.height - textInsets.top - textInsets.bottom;
Then it becomes easy to scroll:
// 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;
Some numbers for reference on what the different sizes represent for an empty 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)
Extend UIScrollView to add a scrollToBottom method:
extension UIScrollView {
func scrollToBottom(animated:Bool) {
let offset = self.contentSize.height - self.visibleSize.height
if offset > self.contentOffset.y {
self.setContentOffset(CGPoint(x: 0, y: offset), animated: animated)
}
}
}
To scroll to the bottom end, we have to work with the target view maximum height.
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)
As explained here
https://janeshswift.com/ios/swift/how-to-scroll-to-a-position-programmatically-in-uiscrollview/
We can create a custom UIScrollView extension as
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
}
}
Use It as --
DispatchQueue.main.async {
self.itemsScrollView.scrollToBottom()
}
Xamarin.iOS version for UICollectionView of the accepted answer for ease in copying and pasting
var bottomOffset = new CGPoint (0, CollectionView.ContentSize.Height - CollectionView.Frame.Size.Height + CollectionView.ContentInset.Bottom);
CollectionView.SetContentOffset (bottomOffset, false);

Resources