Animating UITableViewCells one by one - objective-c

I am trying animation, where the UITableView is already in place,but the subview (which itself contains the cell's content view) for each of the UITableViewCells is outside the window bounds. It is outside the screen. When the view loads, the cell animate from left to right, one by one, till the rightmost x value of the frame touches the rightmost x value of the UITableView.
The animation is such that, once first cell takes off, the second cell takes off before the first cell is finished with it's animation. Similarly, the third cell takes off before the second is finished with it's animation. However, i am not able to achieve this, and i all my rows animate all-together.
-(void)animateStatusViewCells:(SupportTableViewCell *)cell
{
__block CGPoint center;
[UIView animateWithDuration:0.55 delay:0.55 options:UIViewAnimationOptionCurveEaseIn animations:^{
center = cell.statusView.center;
center.x += (cell.frame.size.width - 20);
cell.statusView.center = center;
}completion:^(BOOL success){
NSLog(#"Translation successful!!!");
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//[self animateStatusViewCells:cell];
});
}];
}
-(void)animateSupportTableView:(UITableView *)myTableView
{
NSMutableArray *cells = [[NSMutableArray alloc] init];
NSInteger count = [myTableView numberOfRowsInSection:0];
for (int i = 0; i < count; i++) {
[cells addObject:[myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]]];
}
for (SupportTableViewCell *cell in cells) {
[self animateStatusViewCells:cell];
}
}
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
[self animateSupportTableView:_statusTableView];
}
Here's the initWithStyle method for the custom UITableViewCell:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
_statusView = [[UIView alloc] initWithFrame:self.frame];
self.contentView.backgroundColor = [UIColor greenColor];
self.contentView.alpha = 0.7;
CGPoint cellCenter = self.center;
cellCenter.x = self.center.x - (self.frame.size.width - 20);
_statusView.center = cellCenter;
[self addSubview:_statusView];
[_statusView addSubview:self.contentView];
}
return self;
}

You need to use a different delay value for each animation. Instead of using a constant delay of .55, pass in the cell number to your animate method, and use something like:
CGFloat delay = .55 + cellNumber * cellDelay;
[UIView animateWithDuration: 0.55 delay: delay options:UIViewAnimationOptionCurveEaseIn animations:
^{
//animation code
}
];

For what its worth, this is a clean solution:
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
let trans = CATransform3DMakeTranslation(-cell.frame.size.width, 0.0, 0.0)
cell.layer.transform = trans
UIView.beginAnimations("Move", context: nil)
UIView.setAnimationDuration(0.3)
UIView.setAnimationDelay(0.1 * Double(indexPath.row))
cell.layer.transform = CATransform3DIdentity
UIView.commitAnimations()
}

try this
declare this somewhere.
int c=0;
-(void)animateStatusViewCells:(SupportTableViewCell *)cell
{
__block CGPoint center;
[UIView animateWithDuration:0.55 delay:0.55 options:UIViewAnimationOptionCurveEaseIn animations:^{
center = cell.statusView.center;
center.x += (cell.frame.size.width - 20);
cell.statusView.center = center;
}completion:^(BOOL success){
c++;
if(c<[cells count]){
[self animateStatusViewCells:[cells objectAtIndex:c]];
}
}];
}
-(void)animateSupportTableView:(UITableView *)myTableView
{
NSMutableArray *cells = [[NSMutableArray alloc] init];
NSInteger count = [myTableView numberOfRowsInSection:0];
for (int i = 0; i < count; i++) {
[cells addObject:[myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]]];
}
[self animateStatusViewCells:[cells objectAtIndex:c]];
}

Related

NSMutableArray not holding UIImages properly?

I have enabled my Cocoa Touch app to be navigable by swiping left or right to alter positions in history. The animation is kind of done like Android's "card" style. Where swiping to the left (<--) just moves the current screen image out of the way, while showing the previous view beneath it.
This works fine, but when I want to swipe the other way (-->), to go back, I need to get the previous image, and move that over the current view. Now, I had this working if I only store the previous image, but what if I go <-- a few times, then I will not have enough images.
So, the solution is obvious, use an NSMutableArray and just throw the latest image at the front of the array, and when you swipe the other way, just use the first image in the array. However, the image never shows when I start the animation. It just shows nothing. Here's the required methods you should see:
-(void)animateBack {
CGRect screenRect = [self.view bounds];
UIImage *screen = [self captureScreen];
[imageArray insertObject:screen atIndex:0]; //Insert the screenshot at the first index
imgView = [[UIImageView alloc] initWithFrame:screenRect];
imgView.image = screen;
[imgView setHidden:NO];
NSLog(#"Center of imgView is x = %f, y = %f", imgView.center.x, imgView.center.y);
CGFloat startPointX = imgView.center.x;
CGFloat width = screenRect.size.width;
NSLog(#"Width = %f", width);
imgView.center = CGPointMake(imgView.center.x, imgView.center.y);
[self.view addSubview: imgView];
[self navigateBackInHistory];
[UIView animateWithDuration:.3 animations:^{
isSwiping = 1;
imgView.center = CGPointMake(startPointX - width, imgView.center.y);
} completion:^(BOOL finished){
// Your animation is finished
[self clearImage];
isSwiping = 0;
}];
}
-(void)animateForward {
CGRect screenRect = [self.view bounds];
//UIImage *screen = [self captureScreen];
UIImage *screen = [imageArray objectAtIndex:0]; //Get the latest image
imgView = [[UIImageView alloc] initWithFrame:screenRect];
imgView.image = screen;
[imgView setHidden:NO];
NSLog(#"Center of imgView is x = %f, y = %f", imgView.center.x, imgView.center.y);
CGFloat startPointX = imgView.center.x;
CGFloat width = screenRect.size.width;
NSLog(#"Width = %f", width);
imgView.center = CGPointMake(imgView.center.x - width, imgView.center.y);
[self.view addSubview: imgView];
[UIView animateWithDuration:.3 animations:^{
isSwiping = 1;
imgView.center = CGPointMake(startPointX, imgView.center.y);
} completion:^(BOOL finished){
// Your animation is finished
[self navigateForwardInHistory];
[self clearImage];
isSwiping = 0;
}];
}
-(void)clearImage {
[imgView setHidden:YES];
imgView.image = nil;
}
-(void)navigateBackInHistory {
[self saveItems:self];
[self alterIndexBack];
item = [[[LEItemStore sharedStore] allItems] objectAtIndex:currentHistoryIndex];
[self loadItems:self];
}
-(void)navigateForwardInHistory {
[imageArray removeObjectAtIndex:0]; //Remove the latest image, since we just finished swiping this way.
[self saveItems:self];
[self alterIndexForward];
item = [[[LEItemStore sharedStore] allItems] objectAtIndex:currentHistoryIndex];
[self loadItems:self];
}
Note that imgView is a class-level UIImageView and imageArray is a class level array.
Any ideas? Thanks.
Edit
Here's the code at the top of my .m to initalize it. Still does not work.
.....
NSMutableArray *imageArray;
- (void)viewDidLoad
{
[super viewDidLoad];
imageArray = [imageArray initWithObjects:nil];
It looks like you forgot to create the array. Something like this at the appropriate time would do (assuming ARC):
imageArray = [NSMutableArray array];
Glad that worked out.

UIScrollView flickering with fixed subviews

I use the following code to make "fixed" row headers in my UIScrollView descendant. It works well with the Simulator, but unfortunately, it flickers on the iPad. (To the left of the row header views, a white 1px line appears and disappears.) What can be improved?
- (void)initSubviews
{
const int ROW_COUNT = 20;
rowHeaderViews = [[NSMutableArray alloc]initWithCapacity:ROW_COUNT];
rowViews = [[NSMutableArray alloc]initWithCapacity:ROW_COUNT];
[self setContentSize:CGSizeMake(2000, [self frame].size.height)];
for (int i = 0; i < ROW_COUNT; i++)
{
UIView *header = [self createRowHeaderViewForRowNum:i];
[rowHeaderViews addObject:header];
UIView *row = [self createRowViewForRowNum:i];
[rowViews addObject:row];
[self addSubview:row];
[self addSubview:header];
}
[self layoutSubviews];
}
- (void)layoutSubviews
{
int x = [self contentOffset].x;
for (UIView *view in rowHeaderViews) {
[view setFrame:CGRectMake(x, view.frame.origin.y, view.frame.size.width, view.frame.size.height)];
}
}
- (UIView *)createRowHeaderViewForRowNum: (int)rowNum
{
UILabel *view = [[UILabel alloc]initWithFrame:CGRectMake(0, rowNum * 20, 200, 20)];
[view setBackgroundColor:[UIColor colorWithWhite:0.8*(20-rowNum)/20 alpha:1]];
[view setText:[NSString stringWithFormat:#"Row Header %d", rowNum]];
return view;
}
- (UIView *)createRowViewForRowNum: (int)rowNum
{
UILabel *view = [[UILabel alloc]initWithFrame:CGRectMake(200, rowNum * 20, 1800, 20)];
[view setBackgroundColor:[UIColor colorWithRed:rowNum/20.0 green:0 blue:0 alpha:1]];
[view setText:[NSString stringWithFormat:#"Row Content %d", rowNum]];
return view;
}
Thank you very much for any help!
EDIT: The iPad has got a Retina display. When using the Simulator with a "normal" iPad, it does not flicker. When switching the Simulator to a "Retina display" iPad, there is this flickering, too. Maybe this is something about the points/pixels difference?
I found the bug on my own. Sorry for bothering you.
In case anybody else has got the same problem:
contentOffset.x is a float value and contains .5 values for Retina displays.
Assigning it to an int variable in layoutSubviews caused the problem.
This is the fix (note I replaced 'int' with 'CGFloat'):
- (void)layoutSubviews
{
CGFloat x = [self contentOffset].x;
for (UIView *view in rowHeaderViews) {
[view setFrame:CGRectMake(x, view.frame.origin.y, view.frame.size.width, view.frame.size.height)];
}
}

UIScrollView with UIImageview and gestures using transitionFromView acting strange

I made a view which holds a UIScrollview:
self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(10, 65, 300, 188)];
//BackViews will hold the Back Image
BackViews = [[NSMutableArray alloc] init];
for (int i=0; i<BigPictures.count; i++) {
[BackViews addObject:[NSNull null]];
}
FrontViews = [[NSMutableArray alloc] initWithCapacity:BigPictures.count];
[self.pageControl setNumberOfPages:BigPictures.count];
Then I add several UIImageviews containing images:
//BigPictures holds objects of type UIImage
for (int i = 0; i < BigPictures.count; i++) {
UIImageView *ImageView = [[UIImageView alloc] initWithImage:[BigPictures objectAtIndex:i]];
ImageView.frame = [self.scrollView bounds];
[ImageView setFrame:CGRectMake(self.scrollView.frame.size.width * i, ImageView.frame.origin.y, ImageView.frame.size.width, ImageView.frame.size.height)];
//this saves the FrontView for later (flip)
[FrontViews insertObject:ImageView atIndex:i];
[self.scrollView addSubview:test];
}
// Detect Single Taps on ScrollView
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(flip)];
[self.scrollView addGestureRecognizer:tap];
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * BigPictures.count, self.scrollView.frame.size.height);
self.scrollView.pagingEnabled = YES;
self.scrollView.delegate = self;
Ok so far so good. Now the method which does the flipImage part:
- (void)flip {
int currentPage = self.pageControl.currentPage;
UIView *Back = nil;
if ([BackViews objectAtIndex:currentPage] == [NSNull null]) {
//CreateBackView is just creating an UIView with text in it.
Back = [self CreateBackView];
[BackViews replaceObjectAtIndex:currentPage withObject:Back];
[UIView transitionFromView:[[self.scrollView subviews] objectAtIndex:currentPage] toView:[BackViews objectAtIndex:currentPage] duration:0.8 options:UIViewAnimationOptionTransitionFlipFromLeft completion:NULL];
} else {
[UIView transitionFromView:[[self.scrollView subviews] objectAtIndex:currentPage] toView:[FrontViews objectAtIndex:currentPage] duration:0.8 options:UIViewAnimationOptionTransitionFlipFromRight completion:NULL];
[BackViews replaceObjectAtIndex:currentPage withObject:[NSNull null]];
}
[self.view addSubview:Back];
[self rebuildScrollView];
}
This is what rebuildScrollView does:
- (void)rebuildScrollView
{
for (UIView *subview in self.scrollView.subviews) {
[subview removeFromSuperview];
}
for (int i = 0; i < BigPictures.count; i++) {
if ([BackViews objectAtIndex:i] == [NSNull null]) {
[self.scrollView addSubview:[FrontViews objectAtIndex:i]];
} else {
[self.scrollView addSubview:[BackViews objectAtIndex:i]];
}
}
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * BigPictures.count, self.scrollView.frame.size.height);
self.scrollView.pagingEnabled = YES;
self.scrollView.delegate = self;
}
So the behavior is the following:
If I click on the first image (1 of 3 in scrollview) the effect is the way I want it, meaning the frontimage turns around and shows the empty (white) back with some text in the middle
If I click on the second image, the image turns but the back is completely empty showing the grey background of the window. If I scroll to the other images, the still show the front image (as expected)
Now I click on the third image and its the same as 1) great.
Current layout is now [BackView, Nothing, Backview)
Lets run that again. But now I click on the last image and its the same as 2) :(
Any ideas whats going wrong here?
EDIT: Some new findings. I doubled the amount of pictures and this is how Front and Backviews are placed (after flipping each one). P = Picture & B = Backview.
P_1(B_1) - actually the only correct one
P_2(empty - should be B_2)
P_3(B_2 - should be B_3)
P_4(empty - should be B_4)
P_5(B_3 - should be B_5)
P_6(empty - should be B_6)
Did a complete rebuild and now it works. Really strange because I used the exact same code.

How to add sound while UIScrollview is scrolling in iphone sdk?

This is my code for adding sound while UIScrollview is scrolling in iPhone SDK. In this code, how to add the sound while using touch-events in scrolling?
Please give me your idea and suggestion or sample.
const CGFloat kScrollObjHeight = 151.0;
const CGFloat kScrollObjWidth =320.0;
const NSUInteger kNumImages = 5;
- (void)layoutScrollImages
{
UIImageView *view = nil;
NSArray *subviews = [scrollView1 subviews];
CGFloat curXLoc = 0;
for (view in subviews)
{
if ([view isKindOfClass:[UIImageView class]] && view.tag > 0)
{
CGRect frame = view.frame;
frame.origin = CGPointMake(curXLoc, 0);
view.frame = frame;
curXLoc += (kScrollObjWidth);
}
}
[scrollView1 setContentSize:CGSizeMake((kNumImages * kScrollObjWidth), [scrollView1 bounds].size.height)];
}
- (void)viewDidLoad
{
self.view.backgroundColor = [UIColor clearColor];
[scrollView1 setBackgroundColor:[UIColor whiteColor]];
[scrollView1 setCanCancelContentTouches:NO];
scrollView1.indicatorStyle = UIScrollViewIndicatorStyleWhite;
scrollView1.clipsToBounds = YES;
scrollView1.scrollEnabled = YES;
scrollView1.pagingEnabled = YES;
NSUInteger i;
for (i = 1; i <= kNumImages; i++)
{
NSString *imageName = [NSString stringWithFormat:#"snap%d.jpg", i];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
CGRect rect = imageView.frame;
rect.size.height = kScrollObjHeight;
rect.size.width = kScrollObjWidth;
imageView.frame = rect;
imageView.tag = i;
[scrollView1 addSubview:imageView];
[imageView release];
[self layoutScrollImages];
}
[super viewDidLoad];
}
add UIScrollViewDelegate to your interface and then play sound while the scrolling is in task in scrollViewWillBeginDragging state and stop scrolling while in scrollViewDidEndDragging state.
You can use AVAudioPlayer to play sound on iOS devices
UPDATE:
Tells the delegate when the scroll view is about to start scrolling the content.
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
Also, Tells the delegate when dragging ended in the scroll view.
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
Implement these in your code & put in your custom behavior
you mast use UIScrollViewDelegate method
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//play sound here
}

NSMatrix with multiple toggle buttons?

I am trying to create an NSMatrix of NSButtonCells where between zero and four buttons can be selected (toggled on). I have tried the following (test) code, but am not sure how I can provide the functionality I require. Perhaps it's not possible with NSMatrix and I need to look at an alternative control, or create my own?
#interface MatrixView : NSView
{
NSScrollView *_scrollView;
NSMatrix *_matrixView;
}
#end
#implementation MatrixView
- (id)initWithFrame:(NSRect)frameRect
{
NSLog(#"initWithFrame. frameRect=%#", NSStringFromRect(frameRect));
self = [super initWithFrame:frameRect];
if (self != nil)
{
_scrollView = [[NSScrollView alloc] initWithFrame:NSMakeRect(0, 0, frameRect.size.width, frameRect.size.height)];
[_scrollView setBorderType:NSNoBorder];
[_scrollView setHasVerticalScroller:YES];
[_scrollView setHasHorizontalScroller:NO];
[_scrollView setAutoresizingMask:NSViewWidthSizable|NSViewHeightSizable];
NSSize contentSize = [_scrollView contentSize];
contentSize.height = 300;
// Make it 3 x however-many-buttons-will-fit-the-height
CGFloat gap = 8.0;
CGFloat width = (contentSize.width / 3.0) - (gap * 2.0);
NSUInteger rows = (contentSize.height / (width + gap));
NSLog(#"width=%f, rows=%lu", width, rows);
NSButtonCell *prototype = [[NSButtonCell alloc] init];
[prototype setTitle:#"Hello"];
[prototype setButtonType:NSToggleButton];
[prototype setShowsStateBy:NSChangeGrayCellMask];
_matrixView = [[NSMatrix alloc] initWithFrame:NSMakeRect(0, 0, contentSize.width, contentSize.height)
mode:NSListModeMatrix
prototype:prototype
numberOfRows:rows
numberOfColumns:3];
[_matrixView setCellSize:NSMakeSize(width, width)];
[_matrixView setIntercellSpacing:NSMakeSize(gap, gap)];
[_matrixView setAllowsEmptySelection:YES];
[_matrixView sizeToCells];
[_scrollView setDocumentView:_matrixView];
[self addSubview:_scrollView];
[self setAutoresizesSubviews:YES];
[prototype release];
}
return self;
}
...
I got this to work with the following subclass of NSMatrix. I added one property, onCount, to keep track of how many buttons were in the on state:
#implementation RDMatrix
#synthesize onCount;
-(id) initWithParentView:(NSView *) cv {
NSButtonCell *theCell = [[NSButtonCell alloc ]init];
theCell.bezelStyle = NSSmallSquareBezelStyle;
theCell.buttonType = NSPushOnPushOffButton;
theCell.title = #"";
if (self = [super initWithFrame:NSMakeRect(200,150,1,1) mode:2 prototype:theCell numberOfRows:4 numberOfColumns:4]){
[self setSelectionByRect:FALSE];
[self setCellSize:NSMakeSize(40,40)];
[self sizeToCells];
self.target = self;
self.action = #selector(buttonClick:);
self.drawsBackground = FALSE;
self.autoresizingMask = 8;
self.allowsEmptySelection = TRUE;
self.mode = NSHighlightModeMatrix;
self.onCount = 0;
[cv addSubview:self];
return self;
}
return nil;
}
-(IBAction)buttonClick:(NSMatrix *)sender {
NSUInteger onOrOff =[sender.selectedCells.lastObject state];
if (onOrOff) {
self.onCount += 1;
}else{
self.onCount -= 1;
}
NSLog(#"%ld",self.onCount);
if (self.onCount == 5) {
[sender.selectedCells.lastObject setState:0];
self.onCount -= 1;
}
}
When you try to select the 5th button it will flash on, but then go off. This could be a problem depending on how you are using the state of these buttons. I just logged them with this method:
-(IBAction)checkMatrix:(id)sender {
NSIndexSet *indxs = [self.mat.cells indexesOfObjectsPassingTest:^BOOL(NSButtonCell *cell, NSUInteger idx, BOOL *stop) {
return cell.state == NSOnState;
}];
NSLog(#"%#",indxs);
}
After Edit: I didn't like the way my first method flashed the button on briefly before turning it off again when you try to click the 5th button. I found what I think is a better solution that involves overriding mouseDown in the matrix subclass (if you want to try this, you should delete the setAction and setTarget statements and delete the buttonClick method):
-(void)mouseDown:(NSEvent *) event {
NSPoint matPoint = [self convertPoint:event.locationInWindow fromView:nil];
NSInteger row;
NSInteger column;
[self getRow:&row column:&column forPoint:matPoint];
NSButtonCell *cell = [self cellAtRow:row column:column];
if (self.onCount < 4 && cell.state == NSOffState) {
cell.state = NSOnState;
self.onCount += 1;
}else if (cell.state == NSOnState) {
cell.state = NSOffState;
self.onCount -= 1;
}
}