UIScrollView within a UIScrollView, how to keep a smooth transition when scrolling between the two - objective-c

I have the following layout (see below), which for most circumstances works just fine. The user is able to scroll within the blue UIScrollView (which for all intents and purposes is a UITableView, but this question generalises this), and then when they've reached the end of this scroll view, they can start scrolling again (they have to take their finger off, and on again, because the inner scroll view rubberbands otherwise), and the 'super' scroll view starts scrolling, revealing the rest of the image.
It's the whole (they have to take their finger off, and on again, because the inner scroll view rubberbands otherwise) that I don't want. Ideally, once the contained UIScrollView reaches the end of its content, I want the superview to take over scrolling straight away, so that the inner scroll view doesn't rubberband.
The same goes when the user is scrolling back up; when the red scrollview reaches the top of it's content, I want the inner blue scroll view to start scrolling up straight away, instead of the red scroll view rubberbanding at the top.
Any idea how? I am able to determine when the scroll views have reached the ends of their content, but I'm not sure how to apply this knowledge to achieve the effect I'm after. Thanks.
// Inner (blue) scroll view bounds checking
if (scrollView.contentOffset.y + scrollView.frame.size.height > scrollView.contentSize.height) { ... }
// Outer (red) scroll view bounds checking
if (scrollView.contentOffset.y < 0) { ... }

Yeah. Ive got a nifty trick for you.
Instead of having your red outlined view a scrollview make it a normal UIView that fills the screen. In that view lay out your scroll view (table view) and image view as they are in your illustration.
Place a scrollview that fills the bounds of the root view (i.e. also fills the screen) above all the other scrollview and image views. Set the content size of this view to be the total content height of all the views you want to scroll through. In otherwords there is an invisible scrollview sitting on top of all your other views and its content size height is inner scrollview (tableview) content size height + image view size height.
The heierarchy should look like this:
Then this scrollview on top that you have made with the really tall content size make its delegate be your view controller. Implement scrollViewDidScroll and we'll work some magic.
Scrollviews basically scroll by adjusting the bounds origin with funky formulas for momentum and stuff. So in our scrollviewDidScroll method we will simply adjust the bounds of the underlying views:
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
//the scroll view underneath (in the container view) will have a max content offset equal to the content height
//but minus the bounds height
CGFloat maxYOffsetForUnderScrollView = self.underScrollView.contentSize.height - self.underScrollView.bounds.size.height;
CGRect scrolledBoundsForContainerView = self.view.bounds;
if (scrollView.contentOffset.y <= maxYOffsetForUnderScrollView) {
//in this scenario we are still within the content for the underScrollView
//so we make sure the container view is scrolled to the top and set the offset for the contained scrollview
self.containerView.bounds = scrolledBoundsForContainerView;
self.underScrollview.contentOffset = scrollView.contentOffset;
return;
}
//in this scenario we have scrolled throug the entirety of the contained scrollview
//set its offset to the max and change the bounds of the container view to scroll everything else.
self.underScrollView.contentOffset = CGPointMake(0, maxYOffsetForUnderScrollView);
scrolledBoundsForContainerView.origin.y = scrollView.contentOffset.y - maxYOffsetForUnderScrollView;
self.containerView.bounds = scrolledBoundsForContainerView;
}
You will find that as scrollViewDidScroll is called every frame of animation that this faux scrolling of the contained views looks really natural.
But wait! I hear you say. That scroll view on top now intercepts ALL touches, and the views underneath it need to be touched as well. I have an interesting solution for that as well.
Set the scrollview on top to be off screen somewhere (i.e. set its frame off screen, but still the same size.) and then in your viewDidLoad method you add the scrollview's panGestureRecogniser to the main view. This will mean that you get all the iOS natural scrolling momentum and stuff without actually having the view on the screen. The contained scroll view will now probably go juddery as its pan gesture recognizer will get called as well (they work differently to UIEvent handling) so you will need to remove it.
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.view addGestureRecognizer:self.scrollview.panGestureRecognizer];
[self.underScrollview removeGestureRecognizer:self.underScrollView.panGestureRecognizer];
//further code to set up content sizes and stuff
}
I had fun making this so heres a link to the sample project on github:
https://github.com/joelparsons/multipleScrollers
EDIT:
To show the scrollbar for the top scrollview when its off the screen no matter where you put it you can set the scrollIndicatorInsets to an inset created like this:
CGPoint scrollviewOrigin = self.scrollview.frame.origin;
self.scrollview.scrollIndicatorInsets = UIEdgeInsetsMake(-scrollviewOrigin.y,0,scrollviewOrigin.y,scrollviewOrigin.x);
*caveat that the scrollview still has to be the right height but I'm sure you get the idea.
And then to make the bar draw outside the scrollview's visible bounds you have to turn off clips to bounds
self.scrollview.clipsToBounds = NO;

OMG. jackslash, you saved my life.
In my case, I need to use three depth of scroll views.
Parent Scroll View
that has a scroll view as one of the children
Child Scroll View: shown as 'Explanation Scroll View / Review Table View / Information Scroll View' in the below image)
Hidden Scroll View
which is distribute own content offset to 'Parent Scroll View' and 'Child Scroll View'
which has content size of whole flatten contents
Screenshot of view hierarchy
After setting view hierarchy, I just need to sync whole flatten content size and distribute content offset properly.
Observable.combineLatest(
overviewStackView.rx.observe(CGRect.self, #keyPath(UIStackView.frame)).unwrap(),
explanationScrollView.rx.observe(CGSize.self, #keyPath(UIScrollView.contentSize)).unwrap()
)
.subscribe(onNext: { [weak self] overviewStackViewFrame, explanationScrollViewContentSize in
guard let self = self else { return }
let totalContentHeight = overviewStackViewFrame.height + self.segmentedControl.frame.height + explanationScrollViewContentSize.height
self.hiddenScrollView.contentSize.height = totalContentHeight
})
.disposed(by: disposeBag)
hiddenScrollView.rx.didScroll
.subscribe(onNext: { [weak self] _ in
guard let self = self else { return }
let currentHiddenScrollViewOffsetY = self.hiddenScrollView.contentOffset.y
let parentScrollViewMaxOffsetY = self.overviewStackView.frame.height
let expectedChildScrollViewOffsetY = max(currentHiddenScrollViewOffsetY - parentScrollViewMaxOffsetY, 0)
self.parentScrollView.contentOffset.y = min(parentScrollViewMaxOffsetY, currentHiddenScrollViewOffsetY)
self.explanationScrollView.contentOffset.y = expectedChildScrollViewOffsetY
})
.disposed(by: disposeBag)

Related

Scrollview vertical only with fixed width in Autolayout

In swift how can I set the width of the scroll view to be the width of the screen size?
I tried setting right leading and trailing bounds, but my aspectscalefill image keeps stretching the entire frame.
I am trying to force the view to be the width of the screen and allow vertical scrolling only.
If you want to make a scroll view with auto layout try this. No code at all so you will have to drag things out of the library to the right of Xcode.
In your view controller drag and place the scroll view size it to whatever you want but it looks like you want to make it the size of the screen. Pin all edges to the edges of the view controller. Pin trailing, leading, top, and bottom.
Now, instead of placing your items in the scroll view, place another view in the scroll view. With this new view you will place all of your items. You will most likely have to move the view up or down to place them all and resize the view. You can then place whatever constraints you want on your items. When all items are in their place, set the frame of the new view back to x = 0 and y = 0.
You will then place constraints as follows. Select the new view and pin to top, bottom, trailing, and leading and then center in container. This will make a constraint that is vertical with some negative number. In the storyboard outline select this constraint and set it to zero.
You will now be able to scroll vertically. Let me know if you have any questions.
I created a single view application, and added a UIScrollView in the storyboard with four constraints (top, left, right, bottom). And I add the following code in the viewDidLoad(). Everything works just fine. My image is only scrolling vertically, but not horizontally. No additional settings are needed.
#IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
// Just as an example, I make a size with same with of the view
// and twice the height of the view.
let size = CGSizeMake(
self.view.frame.size.width,
self.view.frame.size.height * 2);
// Load an image and make a image view
let image = UIImage(named: "im.jpg")!
let imageView = UIImageView(image: image)
imageView.frame = CGRect(
origin: CGPoint(x: 0, y: 0),
size: size);
imageView.contentMode = UIViewContentMode.ScaleToFill;
// Add the image view to scroll view
scrollView.addSubview(imageView)
scrollView.contentSize = size;
}
Your problem i caused by the fact that you add your elements to the scrollView from the storyBoard.
In the storyBoard you need:
1) Add the scrollView, if you need to be in the width of the screen then set it's trailing and leading spaces to superView to 0
2) uncheck the "allow horizontal scrolling" in the attribute inspector
In your code
1) set the scrollView's contentSize to what ever size you want it to be.
1.1) in your code you need to set the size of the contentView like so
scroller.contentSize = CGSizeMake(your width, your height);
This is a very important step, the scrollView will not be able to scroll if you don't set the size. Think about the scrollView as the window and the contentView as the view. If the contentView if the same size as the scrollView then the scrollView can't scroll anywhere (all of the contentView fits into the scrollView) in order to create the scrolling you need to make the contentView bigger then the scrollView itself
2) start adding your elements to the scrollView's contentView by calling
[scroller addSubView:<your view>];
this will add your views to the scrollView's contentView and will be

Scrolling a NSScrollView not working

I'm trying to scroll an NSScrollView to the bottom of the view using this code:
NSPoint newScrollOrigin;
if ([[self.chatScreen documentView] isFlipped]) {
newScrollOrigin=NSMakePoint(0.0,NSMaxY([[self.chatScreen documentView] frame])-NSHeight([[self.chatScreen contentView] bounds]));
} else {
newScrollOrigin=NSMakePoint(0.0,0.0);
}
self.chatScreen.backgroundColor=[NSColor redColor];
[[self.chatScreen documentView] scrollPoint:newScrollOrigin];
which came from here: Apple doucmentation on scrolling
When I run my program, it partially scrolls to the bottom of the view, where the screen shows the top of the view (default starting position) but when I attempt to scroll, it jumps to the bottom of the page, where I can then scroll normally.
If I scroll around to any part of the view, the next time it receives an update (which triggers it to jump back to the bottom) it looks like nothing happened, until you try to scroll, which again causes it to jump back to the bottom of the page.
Thanks in advance.
You need to scroll the clip view and not the document view.
The document view fills out the entire scroll view and the clip view is kind of an overlay which scrolls around deciding which parts are visible.
[[self.chatScreen contentView] scrollToPoint:newScrollOrigin];
Notice the scrollToPoint instead of NSView's layer backed scrollPoint
After you scroll a NSClipView its always good practice to reflectScrolledClipView so that the scrollers update.
- (void)reflectScrolledClipView:(NSClipView *)aClipView;

One direction UIScrollView

I need to have my UISCrollView only accept scrolls in one direction, not only one dimension. The ScrollView contains album art for songs in a playlist on a horizontal direction. It is paged, so each cover has its own page. When the user swipes or drags the cover to the left, the next cover slides in place and the next song is played.
It should not be possible to go back to a previous song, or cover. How can i prevent this behavior?
I tried the following:
- (void)scrollViewDidScroll:(UIScrollView *)scrolledView
{
if(scrollView.contentOffset.x < (pageIndex * 320) - 320)
[scrollView setContentOffset:CGPointMake((pageIndex * 320) - 320, 0)];
}
But if i do a quick slide to the "previous" direction, the cover will slide about 150px to the "next" direction, strange.
I have also tried removing the previous covers with removeFromSuperview, but this only leaves a black space, dragging can still be done.
Lastly, i tried to move the covers:
-(void) reloadCoverScrollView{
for(int i = 1; i < [scrollView.subviews count]; i++){
[scrollView exchangeSubviewAtIndex:i withSubviewAtIndex:i - 1];
}
[scrollView setNeedsDisplay];
}
How can i accomplish what i want? The ScrollView should behave as if it was always at the first page. Thanks.
You have two options:
you build your own custom view
you change the scrollview behaviour by moving the current page at offset 0
I explain both solutions:
** CUSTOM VIEW (NO SCROLL VIEW) *
What you need here is a scroll view where most of the useful scroll view features are removed: no continuous scrolling (but pagination), no zoom, limited content size (so you are limited to one page).
In my opinion you should make a view controller where you instantiate two views: one is the current view, the other is the next view; the current view is visible, the next view is placed just outside the window. Then you add a single finger pan gesture and by tracking its status (it is a continuous gesture) you can slide the second view on top of the first; when you consider the swipe complete then you will finish the animation. At the end of the animation you set the new page as "first" and render the hidden second page with the next view, and so on...
** KEEP USING SCROLL VIEW **
In such case your view controller that behaves as UIScrollView delegate must behave in such way that the visible page is placed at content offset zero. So let's say you start at page 0 and you have a list of pages in the scroll view: page 1, page 2, ...
As soon as you swipe to page1 and the animation is finished, you immediately translate all view from page 1 by one page on the left (so if your page is 320px wide you will translate all subviews by 320px on the left) and you will remove the subview at page 0. Then you will reset your scroll view content offset to the origin (0,0). So at the end you will have your new page 1 set at position 0, page 2 moved to position 1 and so on. It will be impossible to scroll left but only right.
When you used "removeFromSuperview" you did the right thing but you forgot to translate the subview and reset the content offset.

How to use NSScrollview?

I can't figure out how to actually use NSScrollview. I dragged the scroll view object onto an NSWindow in the interface builder. I then dragged some NSButtons onto the scroll view. My question is:
How do I actually make it scroll down, for example, 2x the original height?
Of course the user can scroll automatically using their UI. I assume what you want to do is to scroll programmatically.
A bit of background: An NSScrollView has a documentView, which is the underlying view that the scroll view shows a part of, and a clipView, which is the view that is shown on the screen. So the clip view is like a window into the document view. To scroll programmatically you tell the document view to scroll itself in the clip view.
You have two options on how to scroll programmatically:
- (void)scrollPoint:(NSPoint)aPoint –– This scrolls the document so the given point is at the origin of the clip view that encloses it.
- (BOOL)scrollRectToVisible:(NSRect)aRect –– This scrolls the document the minimum distance so the entire rectangle is visible. Note: This may not need to scroll at all in which case it returns NO.
So, for example, here is an example from Apple's Scroll View Programming Guide on how to scroll to the bottom of the document view. Assuming you have an IBOutlet called scrollView connected up to the NSScrollView in your nib file you can do the following:
- (void)scrollToBottom
{
NSPoint newScrollOrigin;
if ([[scrollview documentView] isFlipped]) {
newScrollOrigin = NSMakePoint(0.0,NSMaxY([[scrollview documentView] frame])
-NSHeight([[scrollview contentView] bounds]));
} else {
newScrollOrigin = NSMakePoint(0.0,0.0);
}
[[scrollview documentView] scrollPoint:newScrollOrigin];
}

Why do updates on "contentOffset" of a UIScrollView make no effect?

I have a UIScrollView which is scrollable both vertically and horizontally. This view is filled with lots of buttons, each of them with its own width (but all with the same height).
When one of these buttons gets tapped, a slider-like interface is brought to life. If this interface goes over the selected button, the whole scroll view must be scrolled so that the button becomes visible once again.
My app behaves as expected when the Y coordinate of the scroll view's content offset is set to a limit (this limit can be 0 or the view's height). But if the content offset is located in an intermediate vertical position, the scrolling just doesn't seem to happen.
At first, I tried the following approach:
CGPoint newOffset = CGPointMake(self.scrollView.contentOffset.x + horizontalVar,
self.scrollView.contentOffset.y);
[self.scrollView setContentOffset: newOffset animated: YES];
Which didn't work, as I mentioned.
Then, I tried to manually animate the view, using its property setter:
[UIView animateWithDuration: 0.3 animations: ^{
CGPoint newOffset = CGPointMake(self.scrollView.contentOffset.x + horizontalVar, self.scrollView.contentOffset.y);
self.scrollView.contentOffset = newOffset;
}];
That approach produced the following result: if the scroll view is in an intermediate vertical position when one of its buttons gets tapped, the content offset update causes a visual change, but the view almost immediately returns to its original state.
I have no other clues on the subject. Could you please help me?
Maybe it's because you didn't set the ContentSize of your scrollView.