Parallax UIScrollView – handling two views in one scrollViewDidScroll method? - ios

I’m creating a basic parallax effect much like the iOS7 app switcher, using two UIScrollView instances (cardScrollView and tileScrollView). I scroll one alongside the other, at a different rate, like so:
if ([scrollView isEqual:self.tileScrollView]) {
[self.cardScrollView setContentOffset:CGPointMake((self.tileScrollView.contentOffset.x + 110) * TILE_CARD_DELTA,
self.cardScrollView.contentOffset.y)];
}
This works fine when scrolling tileScrollView. However, I’d like the same to work in reverse, meaning I can scroll cardScrollView and have tileScrollView move accordingly. The issue I’m having is that calling setContentOffset actually causes cardScrollView to call scrollViewDidScroll itself, meaning they’re continually trying to set each other at the same time, and all kinds of hell break loose.
Basically, the issue here is that both scrollView instances are relying on the same scrollViewDidScroll, and so I can’t differentiate between the two of them in there.
How can I get around this one?

You are getting reference of both in this method and work as per requirement :
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if (scrollView == self.tileScrollView) {
// do something
}
else {
// do something
}
}

Related

- (void)scrollViewDidScroll:(UIScrollView *)scrollView too slow in iOS 8

I have a problem where scrolling up/down and setting the contentoffset from within scrollviewdidscroll on a secondary scrollview causes a minor jittery behaviour... or more accurately a low frame rate.
I currently rely on scrollViewDidScroll to manage effects such as Parallax in my UIScrollView, these effects are applied by listening for scrollViewDidScroll, but the turn around time for each call of this method is (for some reason), too slow and causes enough of a delay for it to look kind of bad when scrolling.
Interestingly, iOS 9, runs fine.
I've tried alternative methods, such as turning off images or using AsyncDisplayKit but both have no effect on the number of times scrollViewDidScroll is fired.
It looks to me that I may need to rearchitect the way I create the parallax effect, but I'm hesitant to in case there is a quick fix.
First of all - use Xcode Instruments debug tool "Time Profiler" (Xcode menu Product->Profile, then select Time Profiler from instruments).
Don't forget to check there "Invert Call Tree" and "Hide System Libraries" checkmarks, and detect problem place in your code.
After that you can find some solution.
At least you can try to add additional check before setting contentOffset property for second scroll view:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGFloat contentOffsetForSecondScrollView = 123.0; // Calculate second scroll view content offset
// Add additional check, if content offset doesn't change
if (self.secondScrollView.contentOffset.y != contentOffsetForSecondScrollView) {
self.secondScrollView.contentOffset = CGPointMake(0, contentOffsetForSecondScrollView);
}
}
Put all the effects in the below method.
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
Please put below delegate method to improve and detect scroling
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
//Your code here
}

Is there a more efficient way to detect UIScrollView offset?

I made an infinite scrolling calendar in a UIScrollView, where each may can contain up to eight subviews. The function I'm calling inside scrollViewDidScroll() looks like this (simplified):
func addAndRemoveRow(scrollView: UIScrollView) {
if scrollView.contentOffset.y - scrollViewZeroOffsetY < -heightOfDay/2 { // Going back in time.
createRowAtBottom()
removeRowAtTop()
} else if scrollView.contentOffset.y - scrollViewZeroOffsetY > heightOfDay/2 { // Going forward in time.
createRowAtTop()
removeRowAtBottom()
}
}
Functionally, this works perfectly, and in the mode where each row contains a single day, it runs smoothly even on my iPhone 5 (both modes run fluidly on the simulator). However, in the mode where each row contains a week, it's pretty choppy.
It seems like overkill to call addAndRemoveRow() every time the scrollview is moved even a pixel. Is there a way to call it less frequently?
(Alternatively, is there a more optimized way of doing this? I tried using a UICollectionView and it doesn't run any more smoothly.)
I would be curious as to why a UICollectionView didn't help. I have had collectionView's with 100's of cells on the screen at the same time and it has run very smoothly even on 5's.
If you still have your implementation of the collectionView, some things I would check to see if it can help your performance would be:
1: Make sure that you are reusing cells and that your datasource isn't changing dynamically unless it needs too. Also make sure that if you are adding more subviews to a cell that it is done in awakeFromNib instead of when you configure it and reuse your changes if possible.
2: if there is a lag on startup, use estimated size assuming your using iOS8+ and a flow layout #property (nonatomic) CGSize estimatedItemSize NS_AVAILABLE_IOS(8_0);
3: If you'r not using a flow layout make sure you are only returning the correct number of layout attributes for - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect; You should only have to return the attributes for whatever is in the rect.
4: Try not invalidating the layout on bounds change to see if it helps performance.
If you are doing more dynamic things with the view this is a good read: http://www.raizlabs.com/2013/10/animating-items-uicollectionview-2/

Can two UICollectionViews respond to a single gesture?

I have two fullscreen child UICollectionViews. One is a transparent overlay on the other. I'd like them both to respond when I drag around the screen - both of them when it's a horizontal drag and only one of them when it's a vertical drag, a little like some media centre home screens. Is this possible without reimplementing the private UICollectionView gesture recognisers, and if so how?
If not then any pointers to example reimplementations would be appreciated.
Some things I know, or have tried:
I have a pan gesture recogniser on the View Controller with a Delayed Begin that can detect the vertical or horizontal movement before events are sent through to the views.
I know that simply forwarding events from my parent view's touchesBegan: etc. won't work because the touches' view property is set to my parent view, and UITouches can't be copied (naively at least) since they don't implement the NSCopying protocol. Perhaps I can synthesise suitable UITouch events and forward them?
I know I can send scrollToItemAtIndexPath:atScrollPosition:animated: messages manually but I'd prefer to have the natural drag, swipe and snap paging behaviour for the Collections.
Alternatively, is it possible to modify the private gesture recognisers' delegates and implement gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer: - without explicitly accessing private APIs - to allow both collections to see the touches? Is the responder chain smart enough to call this with gesture recognisers from two sibling views?
Another approach might be to manually control the overlay, and not manage it as a Collection View, but Collection Views seem like a more natural fit, and in theory provide the interactivity I'd like out of the box. The box, at the moment, seems to need a crowbar to get in!
This question seems similar (if less explicit), and has no answers. The other questions I've looked at all seem to be about adding pinch, or having subviews of collections also respond to gestures; not quite my situation.
I'm scratching my head a little, so thanks for any pointers.
The short answer is you can't, easily, anyway.
The approach that worked for me is a lot simpler, and cleaner: embed one collection view within another. The containing one is limited to horizontal scrolling, and the overlay one to vertical, both with paging turned on. Both share the same controller as their delegate and datasource, and - since a collection view is a subclass of scroll view - this also keeps track of which container and overlay page we're on in the scrollViewDidEndDecelerating: method:
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
if ([scrollView isEqual:containerCollection]) {
containerNumber = scrollView.contentOffset.x / scrollView.frame.size.width;
}
else {
overlayNumber = scrollView.contentOffset.y / scrollView.frame.size.height;
}
}
The only real bit of trickery was in my cellForItemAtIndexPath: method where, when I instantiate the container cell, I need to register .xibs for reuse (each overlay is different) and use the remembered overlay page and issue both scrollToItemAtIndexPath: and reloadItemsAtIndexPaths: to the embedded overlay collection to get it to appear correctly.
I've managed to keep both cells as separate .xibs as well, with associated convenience classes for any extra data they need (and in the case of the container collection the overlay collection IBOutlet).
And not a gesture recogniser in sight.

UIRefreshControl for "Pull Up" to refresh?

How do I add UIRefreshControl to bottom of a UIColloectionView? That means how does it work when It comes to Scroll up (to see old data or something)?
You can't use UIRefreshControl to do that, but if you're ok with a simpler solution, you could just set up your collection view to automatically load more data when you scroll to the bottom. (Incidentally, this is a far more common user interface ... the pull up to refresh is not common, but automatically retrieving more data when you hit the bottom is.)
The most primitive rendition of that would be to respond to the UIScrollViewDelegate method and determine if you've scrolled to the bottom of the collection view (which is, itself, a subclass of the UIScrollView):
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if ((scrollView.contentOffset.y + scrollView.frame.size.height) >= scrollView.contentSize.height)
{
if (!self.isLoadingMoreData)
{
self.loadingMoreData = YES;
// proceed with the loading of more data
}
}
}
Even better, if you have more data to load, show a cell at the bottom, that says "please wait, loading more data", perhaps with a UIActivityIndicatorView. For example, if you have more data to load, add a section to the end with this one cell. If you format this additional cell properly (e.g. a single cell that goes all the way across the collection view), it could definitely render the effect you're looking for.
Here is a CCBottomRefreshControl category for UIScrollView class (parent of UICollectionView class) that implements bottomRefreshControl property. It's compatible with both iOS 6 and 7 native refresh controls.
You can't. You can't really customise UIRefreshControl at all.

UIPanGestureRecognizer.maximumNumberOfTouches not respected in nested scroll views?

I have a root UIScrollView that only scrolls vertically, this scrollview represents rows in my jagged grid. I have configured this scroll view's pan gesture recognizer for two touches for both minimum and maximum number of touches requires.
Inside this scrollview I have one or more UIScrollView instances that only scrolls horizontally, these scrollviews each represent a single row in my jagged grid view. I have configured the pan gesture recognizers for all of these scroll views for one touch minimum, and two touches maximum.
So far it works, I get a nice jagged grid view where I can scroll vertically between rows, and horizontally to scroll each row independently. I have intentionally set to minimum number of touches as 2, as not to inter fear with scrolling if I add fro example a UITableView as a subview for any of cell within this jagged grid view (cell == a position defined by a row and column in that row).
Using a UITableView as a cell works, the table view works as expected that is. But scrolling with two fingers also scrolls inside the table view, not at the root scroll view for vertically scrolling between rows.
I have tried configuring the table views pan gesture recognizer to allow a maximum of one touches, in hope that two finger touches would be ignored. This does not work, the maximumNumberOfTouches property of the table view's pan gesture recognizer seams to be ignored.
What could I have done wrong?
A screen shot displaying the layout to clarify what I have done:
Multiple scrolling tends to get tricky, and I don't for sure, but I think Apple does not encourage this. Even so, I still think it's possible. It may be that vertical scrolling on the table view gets mixed with the scroll view vertical scrolling or something else.
Try checking if the delegates for the gesture recognizers are correctly set.
Another way around this is:
- having a Scroll view with buttons, from which you can open popovers with custom controllers (insert there whatever you want).
- create a big UITableViewController and setting the cell's contents as scrollviews etc. I think you could get the same result.
My advice is not to get stuck on just one method, when there could be others more simpler and more intuitive.
TableViews on Scroll views are generally not a great idea. When a TableView receives the touches, even if doesn't need to do anything with it, it won't send them to it's superView.
You might wanna try either of these 2 things:
In your TableView you should send the touches to your superView manually and let them handle them appropriately. I've seen this method being used in one of my side-projects but I'm not able to post an example of it at this time.
The second thing might be easier to implement. Since TableView is a subclass of ScrollView you can call upon the delaysContentTouches of those TableViews. This property will delay the touch-down even on that TableView until it can determine if scrolling is the intent, as is written in the AppleDocs: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIScrollView_Class/Reference/UIScrollView.html#//apple_ref/occ/cl/UIScrollView
Let me know if either of the 2 ways works for you, I'm quite curious about this subject generally.
But don't you try some tricks rather than implementing all such changes :
1) By Default, disable the scrolling of the TableView when the view is created.
2) Once the view gets generated, Recognize the gestures whether its Scrolling using single or multiple touches, if user touch the Child Scrollview.Look out the tag ,based on gestures, you can enable the Scrolling of Tableview.
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//Get the tag of ScrollView
// Check for the Parent as well as Child SCrollview.
// If its child, just enable the scrolling of tableView.
}
- (void)tapAction:(UIGestureRecognizer *)gestureRecognizer
{
// CGPoint *poit = [Tile locationInView:gestureRecognizer.view];
/// [[[gestureRecognizers.view] objectAtIndex:0] removeFromSuperview];
// imageContent = [[UIImageView alloc]initWithFrame:CGRec tMake(0, 0, 200, 250)];
// [imageContent setImage:[UIImage imageNamed:#"Default.png"]];
NSLog(#"You tapped # this :%d",gestureRecognizer.view.tag);
//Regonize the gestures
}
There may be some unnecessary code since, there is no code snippet with your question.I gave a try & showed a trick if that could work for you & solve the problem. ;)
Try this link and pay attention to how they solve nested views.
Remember the best Practices for Handling Multitouch Events:
When handling events, both touch events and motion events, there are a few recommended techniques and patterns you should follow.
Always implement the event-cancellation methods.
In your implementation, you should restore the state of the view to what it was before the current multitouch sequence, freeing any transient resources set up for handling the event. If you don’t implement the cancellation method your view could be left in an inconsistent state. In some cases, another view might receive the cancellation message.
If you handle events in a subclass of UIView, UIViewController, or (in rare cases) UIResponder,
You should implement all of the event-handling methods (even if it is a null implementation).
Do not call the superclass implementation of the methods.
If you handle events in a subclass of any other UIKit responder class,
You do not have to implement all of the event-handling methods.
But in the methods you do implement, be sure to call the superclass implementation. For example,
[super touchesBegan:theTouches withEvent:theEvent];
Do not forward events to other responder objects of the UIKit framework.
The responders that you forward events to should be instances of your own subclasses of UIView, and all of these objects must be aware that event-forwarding is taking place and that, in the case of touch events, they may receive touches that are not bound to them.
Custom views that redraw themselves in response to events should only set drawing state in the event-handling methods and perform all of the drawing in the drawRect: method.
Do not explicitly send events up the responder (via nextResponder); instead, invoke the superclass implementation and let the UIKit handle responder-chain traversal.

Resources