I want to create UIScrollView with scrolling buttons.So when user press left arrow button, scroll must scroll properly.
The issue is: when I click button 3 times quickly scroll can't scroll properly (because of many calls of scrollRectToVisible). May be I can stop current animation before next animation?
P.S. If I set [self scrollScrollViewToIndex:index animated:NO] everything works properly, but I need animation
Here is my code:
- (void)scrollScrollViewToIndex:(int)index animated:(BOOL)animated
{
NSLog(#"scrolled to index: %d", index);
CGFloat offsetX = CGRectGetWidth(_scrollMain.frame) * index;
CGRect scrollRect = CGRectMake(offsetX, 0, CGRectGetWidth(_scrollMain.frame), CGRectGetHeight(_scrollMain.frame));
[_scrollMain scrollRectToVisible:scrollRect animated:animated];
// [self.scrollMain setContentOffset:CGPointMake(offsetX, 0) animated:animated];
}
- (IBAction)leftArrowPressed:(id)sender
{
int indexOfVoucher = [_arrayVouchers indexOfObject:_voucher];
indexOfVoucher--;
self.voucher = [_arrayVouchers objectAtIndex:indexOfVoucher];
[self updateViewWithVoucherWithScrolling:YES];
}
- (IBAction)rightArrowPressed:(id)sender
{
int indexOfVoucher = [_arrayVouchers indexOfObject:_voucher];
indexOfVoucher++;
self.voucher = [_arrayVouchers objectAtIndex:indexOfVoucher];
[self updateViewWithVoucherWithScrolling:YES];
}
- (void)updateViewWithVoucherWithScrolling:(BOOL)withScrolling
{
int indexOfVoucher = [_arrayVouchers indexOfObject:_voucher];
_leftArrowButton.hidden = _rightArrowButton.hidden = NO;
if (indexOfVoucher == 0)
{
_leftArrowButton.hidden = YES;
}
else if (indexOfVoucher == [_arrayVouchers count] - 1)
{
self.rightArrowButton.hidden = YES;
}
if (withScrolling)
{
[self scrollScrollViewToIndex:indexOfVoucher animated:YES];
}
}
update:
working code according to Mar0ux's advice
- (void)scrollScrollViewToIndex:(int)index animated:(BOOL)animated
{
NSLog(#"scrolled to index: %d", index);
CGFloat offsetX = CGRectGetWidth(_scrollMain.frame) * index;
if (animated)
{
[UIView animateWithDuration:0.5
delay:0.0
options:UIViewAnimationCurveEaseInOut | UIViewAnimationOptionBeginFromCurrentState //Multiple options
animations:^ {
// [self.scrollMain setContentOffset:CGPointMake(offsetX, 0) animated:NO];
CGRect scrollRect = CGRectMake(offsetX, 0, CGRectGetWidth(_scrollMain.frame), CGRectGetHeight(_scrollMain.frame));
[_scrollMain scrollRectToVisible:scrollRect animated:NO];
}
completion:^ (BOOL finished) {
}];
}
else
{
CGRect scrollRect = CGRectMake(offsetX, 0, CGRectGetWidth(_scrollMain.frame), CGRectGetHeight(_scrollMain.frame));
[_scrollMain scrollRectToVisible:scrollRect animated:NO];
}
}
You can always animate the contentOffset property yourself and use UIViewAnimationOptionBeginFromCurrentState option. As soon as the second animation begins, the first will end, and by using current state option, the second animation will start from where the first left off.
A few suggestions:
1) do you really want the user hammering on the button while its scrolling? If so then I suggest that your UI design may need redesign.
2) when you perturb the UI in an action method, its best to post other UI actions by dispatching a block with the code to the main queue - the button hiliting will look better.
3) in your specific case, you could in the action method disable the button, then re-enable it when the scrolling has stopped.
Related
I am having some issues with some animation stuff in an iPad application. I have four UIButtons that are on the screen when the app launches.
I basically want the app to load and the four buttons to animate into view one at a time from the top of the screen into place.
I have the following which kind of animates it but I am struggling with it.
-(void)viewWillAppear:(BOOL)animated
{
CGPoint newLeftCenter = CGPointMake( 15.0f + myCocoButton.frame.size.width / 2.0f, myCocoButton.center.y);
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:4.0f];
myCocoButton.center = newLeftCenter;
[UIView commitAnimations];
}
The current code that I have does animate the button but not in the way I want. I can't get my head around how to actually place it exactly where I want it.
In your storyboard, lay out your buttons in their final positions.
In viewWillAppear:, save the location of each button and move the button off-screen:
#implementation MyViewController {
CGPoint _button0TrueCenter;
CGPoint _button1TrueCenter;
CGPoint _button2TrueCenter;
CGPoint _button3TrueCenter;
}
static void moveButtonAndSaveCenter(UIButton *button, CGPoint offscreenCenter, CGPoint *trueCenter) {
*trueCenter = button.center;
button.center = offscreenCenter;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
if (animated) {
moveButtonAndSaveCenter(self.button0, CGPointMake(-100, 100), &_button0TrueCenter);
moveButtonAndSaveCenter(self.button1, CGPointMake(420, 100), &_button1TrueCenter);
moveButtonAndSaveCenter(self.button2, CGPointMake(-100, 200), &_button2TrueCenter);
moveButtonAndSaveCenter(self.button3, CGPointMake(420, 200), &_button3TrueCenter);
}
}
Then in viewDidAppear:, animate them back to their original locations:
static void animateButton(UIButton *button, CGPoint newCenter, NSTimeInterval delay) {
[UIView animateWithDuration:.25 delay:delay options:0 animations:^{
button.center = newCenter;
} completion:nil];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
if (animated) {
animateButton(self.button0, _button0TrueCenter, 0);
animateButton(self.button1, _button1TrueCenter, 0.2);
animateButton(self.button2, _button2TrueCenter, 0.4);
animateButton(self.button3, _button3TrueCenter, 0.6);
}
}
Assuming you have your buttons in an array, you could do something like this (your items should be in the correct end positions in the nib)
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
CGAffineTransform transform = CGAffineTransformMakeTranslation(0.f, -200.f);
[self.buttons enumerateObjectsUsingBlock:^(UIButton *button, NSUInteger idx, BOOL *stop) {
button.transform = transform; // This translates the view's off the top of the screen
[UIView animateWithDuration:0.25f
delay:0.25f * idx
options:UIViewAnimationCurveEaseOut // No point doing easeIn as the objects are offscreen anyway
animations:^{
button.transform = CGAffineTransformIdentity;
} completion:nil];
}];
}
This will animate every time. You may need to add an ivar to stop this happening and just set it to YES after this has run once. The problem I found when I was just messing around is that when it was calling viewDidAppear: animated was NO on first load, so I couldn't use that BOOL as a check
I've written a blog post about this subject: http://www.roostersoftstudios.com/2011/07/01/iphone-dev-performing-sequential-uiview-animations/
and I have a sample project there.
You can just chain the animations where when one finishes it calls the function of the next animation. Can you be more specific about the exact issues you are having?
I'm trying to make photo album like photo.app in iPhone. I know We have 'PhotoScroller' example from Apple (which I don't think I can copy and paste the code here due to the Non Disclosure Agreement, plus it's bit biggy to play with at the moment). However I found an another example from random search and it seems like based on the PhotoScroller (very simplified tough). The link for the example is ;
http://ykyuen.wordpress.com/2010/05/22/iphone-uiscrollview-with-paging-example/
I applied this code to my project to make photo album (and it scrolls, at least), but I found a problem. The problem is I cannot start from the page I want. The sample code only starts scrolling with Page One. Code itself seems 'really' simple but somehow I just cannot make it start from the page I choose.
Here is main part of the sample code that I found on the Internet. You can of course download the project the link above.
- (void)viewDidLoad {
NSLog(#"ScrollViewWithPagingViewContrller :: viewDidLoad");
[super viewDidLoad];
// view controllers are created lazily
// in the meantime, load the array with placeholders which will be replaced on demand
NSMutableArray *controllers = [[NSMutableArray alloc] init];
for (unsigned i = 0; i < kNumberOfPages; i++) {
[controllers addObject:[NSNull null]];
}
self.viewControllers = controllers;
[controllers release];
// a page is the width of the scroll view
scrollView.pagingEnabled = YES;
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * kNumberOfPages, scrollView.frame.size.height);
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.scrollsToTop = NO;
scrollView.delegate = self;
pageControl.numberOfPages = kNumberOfPages;
pageControl.currentPage = 0;
// pages are created on demand
// load the visible page
// load the page on either side to avoid flashes when the user starts scrolling
[self loadScrollViewWithPage:0];
[self loadScrollViewWithPage:1];}
- (void)loadScrollViewWithPage:(int)page {
NSLog(#"ScrollViewWithPagingViewContrller :: loadScrollViewWithPage");
if (page < 0) return;
if (page >= kNumberOfPages) return;
// replace the placeholder if necessary
MyViewController *controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller == [NSNull null]) {
controller = [[MyViewController alloc] initWithPageNumber:page];
[viewControllers replaceObjectAtIndex:page withObject:controller];
//
[controller release];
}
// add the controller's view to the scroll view
if (nil == controller.view.superview) {
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
controller.view.frame = frame;
[scrollView addSubview:controller.view];
}
}
- (void)scrollViewDidScroll:(UIScrollView *)sender {
NSLog(#"ScrollViewWithPagingViewContrller :: scrollViewDidScroll");
// We don't want a "feedback loop" between the UIPageControl and the scroll delegate in
// which a scroll event generated from the user hitting the page control triggers updates from
// the delegate method. We use a boolean to disable the delegate logic when the page control is used.
if (pageControlUsed) {
// do nothing - the scroll was initiated from the page control, not the user dragging
return;
}
// Switch the indicator when more than 50% of the previous/next page is visible
CGFloat pageWidth = scrollView.frame.size.width;
int page = floor(scrollView.contentOffset.x - pageWidth / 2) / pageWidth;
pageControl.currentPage = page;
// load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
// A possible optimization would be to unload the views+controllers which are no longer visible
}
// At the begin of scroll dragging, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
NSLog(#"ScrollViewWithPagingViewContrller :: scrollViewWillBeginDragging");
pageControlUsed = NO;
}
// At the end of scroll animation, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
NSLog(#"ScrollViewWithPagingViewContrller :: scrollViewDidEndDecelerating");
pageControlUsed = NO;
}
- (IBAction)changePage:(id)sender {
NSLog(#"ScrollViewWithPagingViewContrller :: changePage");
int page = pageControl.currentPage;
// load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
// update the scroll view to the appropriate page
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
[scrollView scrollRectToVisible:frame animated:YES];
// Set the boolean used when scrolls originate from the UIPageControl. See scrollViewDidScroll: above.
pageControlUsed = YES;
}
I have implemented photo album view where in first view i have shown all the thumbnail images and on clicking each image it gives its full screen view. you also scroo the images.
See this answer.
All the best.
The answer is
scrollView1.contentOffset = CGPointMake( , );
quite simple. spent lot of time.
I'm sure I've seen code for this somewhere this somewhere, but I can't find it...
I'd like to be able to programatically slide down a UITabBarController... not when transitioning to another view, but within the same view.
If you want to slide the UITabBar down and up you can try something like:
- (IBAction)showHideTabBar:(id)sender {
static BOOL isShowing = YES;
CGRect tabBarFrame = self.tabBarController.tabBar.frame;
if (isShowing) {
tabBarFrame.origin.y += tabBarFrame.size.height;
}
else {
tabBarFrame.origin.y -= tabBarFrame.size.height;
}
isShowing = !isShowing;
[UIView animateWithDuration:0.3 animations:^ {
[self.tabBarController.tabBar setFrame:tabBarFrame];
}];
}
I'm using a UITextView to roughly replicate the SMS text box above the keyboard. I'm using a UITextView instead of a field so that it can expand with multiple lines.
The problem is that, in my UITextView, the correction suggestions pop up below the text, causing them to be partially obscured by the keyboard.
In the SMS app, the suggestions pop up above the text. The placement does not appear to be a property of UITextView, or UITextInputTraits.
Any idea how to replicate this behavior? Thanks!
The problem is that the Keyboard is implemented as a separate UIWindow, rather than as a view within the main UIWindow, so layout with it is tricky. Here are some pointers in the right direction:
Hunt through the application's -windows property to find the private UITextEffectsWindow window and figure out its frame. This is the keyboard
Hunt through the TextView's subviews to find the private UIAutocorrectInlinePrompt view. This is the autocorrect bubble.
Move that subview into a separate wrapper view (added to the TextView) and then move that wrapper view so it's above the above-mentioned keyboard window.
You'll notice two mentions of "private" above. That carries all the relevant caveats. I have no idea why Apple has allowed the problem to persist when even their apps have had to work around it.
By doing the search for the UIAutocorrectInlinePrompt in an overridden or swizzled layoutSubViews it is possible to alter the layout of the correction so that it appears above. You can do this without calling any private APIs by looking for the subs views of particular classes positioned in a way you'd expect them. This example works out which view is which, checks to see that the correction is not already above the text and moves the correction above, and draws it on the window so that it is not bounded by the UITextView itself. Obviously if apple change the underlying implementation then this will fail to move correction. Add this to your overriden or swizzled layoutSubViews implementation.
- (void) moveSpellingCorrection {
for (UIView *view in self.subviews)
{
if ([[[view class] description] isEqualToString:#"UIAutocorrectInlinePrompt"])
{
UIView *correctionShadowView = nil; // [view correctionShadowView];
for (UIView *subview in view.subviews)
{
if ([[[subview class] description] isEqualToString:#"UIAutocorrectShadowView"])
{
correctionShadowView = subview;
break;
}
}
if (correctionShadowView)
{
UIView *typedTextView = nil; //[view typedTextView];
UIView *correctionView = nil; //[view correctionView];
for (UIView *subview in view.subviews)
{
if ([[[subview class] description] isEqualToString:#"UIAutocorrectTextView"])
{
if (CGRectContainsRect(correctionShadowView.frame,subview.frame))
{
correctionView = subview;
}
else
{
typedTextView = subview;
}
}
}
if (correctionView && typedTextView)
{
CGRect textRect = [typedTextView frame];
CGRect correctionRect = [correctionView frame];
if (textRect.origin.y < correctionRect.origin.y)
{
CGAffineTransform moveUp = CGAffineTransformMakeTranslation(0,-50.0);
[correctionView setTransform: moveUp];
[correctionShadowView setTransform: moveUp];
CGRect windowPos = [self convertRect: view.frame toView: nil ];
[view removeFromSuperview];
[self.window addSubview: view];
view.frame = windowPos;
}
}
}
}
}
}
Actually doing
textview.scrollEnabled = NO;
will set the bubble on top of the text... the caveat is that you lose scrolling, in my case it wasn't a problem due to havinng a textfield only for input purposes with character limit
Actually, the keyboard simply uses the result of -[UITextInput textInputView] to determine where to put the correction view (and to ask if your view supports correction). So all you need to do is this:
- (UIView *)textInputView {
for (UIWindow *window in [UIApplication sharedApplication].windows) {
if ([window isKindOfClass:NSClassFromString(#"UITextEffectsWindow")] &&
window != self.window) {
return window;
}
}
// Fallback just in case the UITextEffectsWindow has not yet been created.
return self;
}
Note that you'll likely also need to update -[UITextInput firstRectForRange:] to use the coordinate system of the window / device, so you can do this:
- (CGRect)firstRectForRange:(CoreTextTokenTextRange *)range {
CGRect firstRect = [self firstRectForRangeInternal:range];
return [self convertRect:firstRect toView:[self textInputView]];
}
(In the above context, self is a class that implements UITextInput).
If the bottom of your UITextView clears the keyboard, you should be able to just resize your UITextView to be tall enough to see the corrections. The corrections themselves don't display outside of the UITextView's frame.
If you want to mimic what you are getting in the SMS app (corrections above), you'll probably have to roll your own.
Putting the below method, adjustAutocorrectPromptView in layoutSubviews worked for me in portrait and landscape. I have a category that provides the bottom and top methods on view but you get the idea.
NSArray * subviewsWithDescription(UIView *view, NSString *description)
{
return [view.subviews filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:#"class.description == '%#'", description]]];
}
- (void) adjustAutocorrectPromptView;
{
UIView *autocorrectPromptView = [subviewsWithDescription(self, #"UIAutocorrectInlinePrompt") lastObject];
if (! autocorrectPromptView)
{
return;
}
UIView *correctionShadowView = [subviewsWithDescription(autocorrectPromptView, #"UIAutocorrectShadowView") lastObject];
if (! correctionShadowView)
{
return;
}
UIView *typedTextView = nil; //[view typedTextView];
UIView *correctionView = nil; //[view correctionView];
for (UIView *subview in subviewsWithDescription(autocorrectPromptView, #"UIAutocorrectTextView"))
{
if (CGRectContainsRect(correctionShadowView.frame,subview.frame))
{
correctionView = subview;
}
else
{
typedTextView = subview;
}
}
if (correctionView && typedTextView)
{
if (typedTextView.top < correctionView.top)
{
correctionView.bottom = typedTextView.top;
correctionShadowView.center = correctionView.center;
}
}
}
Make sure your view controller delegate is listening to the notification when the keyboard pops up so that you resize your UITextView so that the keyboard doesn't obscure the UITextView. Then your correction won't be obscured by the keyboard. See:
http://www.iphonedevsdk.com/forum/iphone-sdk-development/12641-uitextview-scroll-while-editing.html
Here is a copy of the code from that page in case the original link is broken:
// the amount of vertical shift upwards keep the Notes text view visible as the keyboard appears
#define kOFFSET_FOR_KEYBOARD 140.0
// the duration of the animation for the view shift
#define kVerticalOffsetAnimationDuration 0.50
- (IBAction)textFieldDoneEditing:(id)sender
{
[sender resignFirstResponder];
}
- (IBAction)backgroundClick:(id)sender
{
[latitudeField resignFirstResponder];
[longitudeField resignFirstResponder];
[notesField resignFirstResponder];
if (viewShifted)
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:kVerticalOffsetAnimationDuration];
CGRect rect = self.view.frame;
rect.origin.y += kOFFSET_FOR_KEYBOARD;
rect.size.height -= kOFFSET_FOR_KEYBOARD;
self.view.frame = rect;
[UIView commitAnimations];
viewShifted = FALSE;
}
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
if (!viewShifted) { // don't shift if it's already shifted
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:kVerticalOffsetAnimationDuration];
CGRect rect = self.view.frame;
rect.origin.y -= kOFFSET_FOR_KEYBOARD;
rect.size.height += kOFFSET_FOR_KEYBOARD;
self.view.frame = rect;
[UIView commitAnimations];
viewShifted = TRUE;
}
return YES;
}
I'm using a UIScrollerView and I found that it tends to "snap" back to a previous position when I scroll it.
I would like to simulate the behavior if the UItableView's scroller, that stays in the position where the user released his finger.
The properties set:
[scroller setCanCancelContentTouches:NO];
scroller.clipsToBounds = YES;
[scroller setScrollEnabled:YES];
scroller.userInteractionEnabled = YES;
scroller.alwaysBounceHorizontal = YES;
scroller.alwaysBounceVertical= NO;
scroller.showsVerticalScrollIndicator = NO;
scroller.scrollsToTop = NO;
scroller.bounces = NO;
scroller.pagingEnabled = NO;
There a few possible reasons for the snap back.
One could be that you have pagingEnabled set to YES which means that when the user lets go their finger, it will snap to the closest page boundary.
Another is that you have the contentSize set incorrectly. This is not the problem if you can actually scroll to the top and bottom and leave it there without it bouncing away.
- (void)scrollViewDidScroll:(UIScrollView *)sender {
int scrollDirection;
if (lastContentOffset > self.scrollView.contentOffset.x){
scrollDirection = RIGHT;
NSLog(#"right");
}
else if (lastContentOffset < self.scrollView.contentOffset.x) {
scrollDirection = LEFT;
NSLog(#"left");
lastContentOffset = self.scrollView.contentOffset.x;
}
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
lastContentOffset = self.scrollView.contentOffset.x;
}