UiCollectionViewCell random images flipping - ios

I have been looking around here for a answer with no success so now ill make a try my self.
Im trying to make a UicollectionView with different cells containing images + an animation with the cells.
I want the cells to do "random flipping" with my images (5 different images)
UIViewAnimationOptionTransitionFlipFromLeft
in a loop with 5-6 sec delay.
the animation i have for the moment is this:
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
[cell.superview bringSubviewToFront:collectionView];
[UIView transitionWithView:cell
duration:1.0
options:UIViewAnimationOptionTransitionFlipFromLeft
animations:^{
[UICollectionViewCell commitAnimations];
cell.transform = CGAffineTransformMakeRotation(0.0);
}
completion:^(BOOL finished) {}];
}
I know that i shouldn't use the didSelectItemAtIndexPath, but i used it just to see if the animation were right.
If you check at this video u can see what i mean, on the windows 8 phone. Youtube video

Ok, I was interested on this idea so I prototyped some code. I needs to be specifically tailored to your needs but it can be a good start. Firstly, you will need to subclass your UICollectionViewCell in order to connect an IBOutlet to your imageView inside the cell. Then you can reference my code snippet to get you started.
- (void)viewDidLoad
{
[super viewDidLoad];
self.imageList = #[#"img1.png", #"img2.png", #"img3.png", #"img4.png"];
}
// This assumes your images are inside your Bundle.
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[NSTimer scheduledTimerWithTimeInterval:4.0
target:self
selector:#selector(updateCells:)
userInfo:nil
repeats:YES];
}
- (void)updateCells:(NSTimer *)timer
{
NSArray *visibleIndexPaths = [self.collectionView indexPathsForVisibleItems];
for (NSIndexPath *indexPath in visibleIndexPaths) {
SubclassCollectionViewCell *cell = (SubclassCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
[UIView transitionWithView:cell
duration:1.0f
options:UIViewAnimationOptionTransitionFlipFromLeft
animations:^{
cell.imageView.image = [self randomImage];
} completion:nil];
}
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"Cell" forIndexPath:indexPath];
return cell;
}
- (UIImage *)randomImage
{
NSInteger randomNumber = arc4random() % [self.imageList count];
return [UIImage imageNamed:[self.imageList objectAtIndex:randomNumber]];
}
Update:
If you want only one cell at a time to randomly flip, you will need to take out the for loop in the updateCells method. Instead, try this:
- (void)updateCells:(NSTimer *)timer
{
NSArray *visibleIndexPaths = [self.collectionView indexPathsForVisibleItems];
NSInteger randomIndex = arc4random() % [visibleIndexPaths count];
NSindexPath *randomIndexPath = [NSIndexPath indexPathForItem:randomIndex inSection:0];
SubclassCollectionViewCell *cell = (SubclassCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
[UIView transitionWithView:cell
duration:1.0f
options:UIViewAnimationOptionTransitionFlipFromLeft
animations:^{
cell.imageView.image = [self randomImage];
}
completion:nil
];
}

Edited post:
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
int interval = 5+(rand() % 6);
int section = 0;
int row = (arc4random() % self.cellList.count);
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
CollectionCell *cell = (CollectionCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
[NSTimer scheduledTimerWithTimeInterval:interval
target:self
selector:#selector(updateCells:)
userInfo:cell
repeats:NO];
NSLog(#"seconds: %d", interval);
NSLog(#"row: %d", row);
}
- (void)updateCells:(NSTimer *)timer{
CollectionCell* cell = [timer userInfo];
[UIView transitionWithView:cell
duration:1.0f
options:UIViewAnimationOptionTransitionFlipFromLeft
animations:^{
cell.collectionImageView.image = [self randomImage];
} completion:nil];
int interval = 5+(rand() % 5);
NSLog(#"speed: %d", interval);
int section = 0;
int row = (arc4random() % self.cellList.count);
NSLog(#"row: %d", row);
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
CollectionCell *newCell = (CollectionCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
[NSTimer scheduledTimerWithTimeInterval:interval
target:self
selector:#selector(updateCells:)
userInfo:newCell
repeats:NO];}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return self.cellList.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGRect frame = self.collectionView.frame;
[collectionView setFrame:frame];
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"ReuseID" forIndexPath:indexPath];
[collectionView setNeedsDisplay];
[self cellTitleAndBackground:cell indexPath:indexPath];
return cell;
}
- (void)cellTitleAndBackground:(CollectionCell *)cell indexPath:(NSIndexPath *)indexPath {
// Get title
NSString *name = [[NSString alloc] initWithFormat:#"%#", self.cellList[indexPath.row]];
// Create title background
UILabel *titleBackground = [[UILabel alloc] initWithFrame:CGRectMake(5, 70, 70, 30)];
titleBackground.backgroundColor = [UIColor blackColor];
titleBackground.alpha = 0.6f;
titleBackground.tag = 70;
[self removeReusedLabel:cell tag:70];
[cell addSubview:titleBackground];
// Create titleLabel
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 70, 70, 30)];
titleLabel.textColor = [UIColor whiteColor];
titleLabel.font = [UIFont boldSystemFontOfSize:12];
titleLabel.text = name;
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.textAlignment = NSTextAlignmentCenter;
titleLabel.tag = 72;
[self removeReusedLabel:cell tag:72];
[cell addSubview:titleLabel];
}
-(void)removeReusedLabel:(CollectionCell *)cell tag:(int)tag {
UILabel *foundLabelBackground = (UILabel *)[cell viewWithTag:tag];
if (foundLabelBackground) [foundLabelBackground removeFromSuperview];
}
- (UIImage *)randomImage
{
// Random image for cells
NSInteger randomNumber = arc4random() % [self.imageList count];
return [UIImage imageNamed:[self.imageList objectAtIndex:randomNumber]];
}

Related

UICollectionView Reorders And Changes Selected Item

I'm currently facing a problem where my collectionView changes the order of my items when they scroll off the screen and switches the selected cell. At the moment they're organized so that they scrolls vertically (and there are two items side by side):
Here is my - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath method:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = #"FriendCell";
FriendsCell *cell = (FriendsCell *)[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
//Friend Object
PFUser *friend = [self.friendsArray objectAtIndex:indexPath.item];
cell.friendId = currentFriend.objectId;
//Setup Cell
if (!cell.isSelected) {
cell.layer.backgroundColor = [UIColor whiteColor].CGColor;
} else {
cell.layer.backgroundColor = FlatGreen.CGColor;
}
//Set Profile Image
if (!cell.profileImageView) {
cell.profileImageView = [UIImageView new];
cell.profileImageView.image = [UIImage imageNamed:#"ProfileImagePlaceholder"];
[cell addSubview:cell.profileImageView];
}
//Set Username
if (!cell.usernameLabel) {
//Set Username Label
cell.usernameLabel = [UILabel new];
cell.usernameLabel.text = friend[#"username"];
cell.usernameLabel.textColor = [UIColor lightGrayColor];
[cell addSubview:cell.usernameLabel];
} else {
if (cell.isSelected) {
cell.usernameLabel.textColor = [UIColor whiteColor];
} else {
cell.usernameLabel.textColor = [UIColor lightGrayColor];
}
}
return cell;
}
didSelectItemAtIndexPath:
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
//Determine the selected friend by using the indexPath
PFUser *selectedFriend = [self.friendsArray objectAtIndex:indexPath.item];
//Add the selected friend's objectId to our array
[self.friendsToAdd addObject:selectedFriend.objectId];
//Show Selected View
FriendsCell *currentCell = (FriendsCell *)[collectionView cellForItemAtIndexPath:indexPath];
//Animate
[UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
//Update
currentCell.layer.backgroundColor = FlatGreen.CGColor;
currentCell.profileImageView.alpha = 0.0;
currentCell.usernameLabel.textColor = [UIColor whiteColor];
} completion:nil];
}
didDeselectItemAtIndexPath:
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
//Determine the selected friend by using the indexPath
PFUser *deselectedFriend = [self.friendsArray objectAtIndex:indexPath.item];
//Remove the deselected friend's objectId from our array
[self.friendsToAdd removeObject:deselectedFriend.objectId];
//Show Deselected View
FriendsCell *currentCell = (FriendsCell *)[collectionView cellForItemAtIndexPath:indexPath];
//Animate
[UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionTransitionFlipFromBottom animations:^{
//Update Card
currentCell.layer.backgroundColor = [UIColor whiteColor].CGColor;
currentCell.profileImageView.alpha = 1.0;
currentCell.usernameLabel.textColor = [UIColor lightGrayColor];
} completion:nil];
}
If anyone can spot why this is happening, I'd really appreciate it!
Try
dequeueReusableCellWithReuseIdentifier:nil

Set UITableViewCell in full screen

I want to set UITableViewCell in full screen when user select cell with bouncing animation. I shared link below. I want same like this.
https://drive.google.com/open?id=0B9k_Shyb5v62eFdxWXhYeXV3a0E
I set view inside cell. But I can't set it in full screen with animation.
Below is my code:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableViewList cellForRowAtIndexPath:indexPath];
int index = [cell.accessibilityIdentifier intValue];
CGFloat delay = 0.0f;
if (indexSelected == (int)indexPath.row)
{
//COLLAPSE
indexSelected = -1111111111;
UIView *viewController = (UIView *)[cell.contentView viewWithTag:TAG_DETAIL_CONTROLLER];
[viewController removeFromSuperview];
tableViewList.frame = frameTableViewList;
[tableView reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationNone];
btnBack.hidden = YES;
indexSelected = -1;
}
else
{
//EXPAND
if (indexSelected < 0)
indexSelected = index;
else
{
int indexPrevious = indexSelected;
indexSelected = (int)indexPath.row;
[tableView reloadRowsAtIndexPaths:#[[NSIndexPath indexPathForRow:indexPrevious inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
delay = 0.3;
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[tableView reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationNone];
CGRect frame = tableViewList.frame;
frame.origin.y = 0;
frame.size.height = CGRectGetHeight(self.view.frame);
tableViewList.frame = frame;
btnBack.hidden = NO;
});
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
cell = [self reuseTableViewCellWithIdentifier:cellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIView *viewController = (UIView *)[cell.contentView viewWithTag:TAG_DETAIL_CONTROLLER];
if (indexSelected >= 0 && indexSelected == (int)indexPath.row)
[self addDiamondDetailView:cell index:(int)indexPath.row];
else
{
if (indexSelected == -1111111111)
{
CGRect frame = cell.frame;
frame.size.height = cellHeight;
cell.frame = frame;
cell.contentView.frame = CGRectMake(0, 0, CGRectGetWidth(cell.frame), CGRectGetHeight(cell.frame));
}
[viewController removeFromSuperview];
}
cell.contentView.clipsToBounds = YES;
return cell;
}
- (void)addDiamondDetailView:(UITableViewCell *)cell index:(int)index
{
DetailVC = [[DetailViewController alloc] initWithNibName:#"DetailViewController" bundle:nil];
DetailVC.selectedStoneInfo = (StoneInfo *)[arrStone objectAtIndex:index];
DetailVC._STONE_DETAIL_TYPE = self._RESULT_PAGE_TYPE == RESULT_MY_CART ? STONE_DETAIL_CART : STONE_DETAIL_RESULT;
DetailVC.delegate = self;
DetailVC.view.tag = TAG_DETAIL_CONTROLLER;
[cell.contentView addSubview:stoneDetailVC.view];
//Cell Frame
CGRect frame = cell.bounds;
frame.size.height = cellDetailHeight;
cell.frame = frame;
cell.contentView.frame = CGRectMake(0, 0, CGRectGetWidth(cell.frame), CGRectGetHeight(cell.frame));
//Stone Detail VC Frame
frame = stoneDetailVC.view.frame;
DetailVC.view.frame = CGRectMake(0, 0, CGRectGetWidth(stoneDetailVC.view.frame), cellDetailHeight);
}
I've added ViewController into cell as sub view. I want to set table cell in view full screen with bounce animation. Please help me.

Table view is not refreshing on real device

I have a problem with a table view.
When I selected row, my height of cell is changing and display some information. If I select a second time, it's closing.
Works like a charm on simulator, but on real device, first part work fine, but when I want close it, he is executing the code but probably not refreshing tableView, because my information stay displayed.
Another problem for real device: my views is not appear.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 4;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.row ==1 &&show == YES) {
return 50 + descLabel;
}else if (indexPath.row == 2 && show2 == YES){
return caracLabel;
}
{
return 50;
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *cellID = #"detailCell";
switch (indexPath.row) {
case 0:
cellID = #"detailCell1";
break;
case 1:
cellID = #"detailCell2";
break;
case 2:
cellID = #"detailCell3";
break;
case 3:
cellID = #"detailCell4";
default:
break;
}
detailCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.label.text = [self.array objectAtIndex:indexPath.row];
cell.image1.image = [UIImage imageNamed:[NSString stringWithFormat:[self.imageArray objectAtIndex:indexPath.row]]];
if (indexPath.row == 1) {
if (show == NO) {
cell.labelDef.hidden =YES;
}
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.row==1) {
if (show == NO ) {
detailCell *cell = [self.tableView dequeueReusableCellWithIdentifier:#"detailCell2" forIndexPath:indexPath];
show=YES;
cell.label.text = [self.array objectAtIndex:indexPath.row];
cell.image1.image = [UIImage imageNamed:[NSString stringWithFormat:[self.imageArray objectAtIndex:indexPath.row]]];
cell.labelDef.text=[self.desc objectAtIndex:pos];
cell.labelDef.sizeToFit;
cell.imageButton.image = [UIImage imageNamed:#"Play_Symbol_copie_5#3x.png"];
cell.labelDef.frame = CGRectMake(10, 50, cell.labelDef.frame.size.width, cell.labelDef.frame.size.height);
cell.labelDef.hidden = NO;
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 50, cell.frame.size.width, cell.labelDef.frame.size.height)];
[view setBackgroundColor:[UIColor whiteColor]];
[cell.contentView addSubview:view];
[cell.contentView addSubview:cell.labelDef];
descLabel = cell.labelDef.frame.size.height ;
// [self.tableView reloadRowsAtIndexPaths:#[[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section]] withRowAnimation:UITableViewRowAnimationMiddle];
[self.tableView reloadRowsAtIndexPaths:#[[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section]]
withRowAnimation:UITableViewRowAnimationNone];
[self.tableView selectRowAtIndexPath:indexPath
animated:NO
scrollPosition:UITableViewScrollPositionNone];
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}else{
detailCell *cell = [self.tableView dequeueReusableCellWithIdentifier:#"detailCell2" forIndexPath:indexPath];
show= NO;
cell.label.text = [self.array objectAtIndex:indexPath.row];
cell.image1.image = [UIImage imageNamed:[NSString stringWithFormat:[self.imageArray objectAtIndex:indexPath.row]]];
cell.imageButton.image = [UIImage imageNamed:#"Play_Symbol_copie_2#3x.png"];
cell.labelDef.hidden = YES;
// [self.tableView reloadRowsAtIndexPaths:#[[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section]] withRowAnimation:UITableViewRowAnimationMiddle];
[self.tableView reloadRowsAtIndexPaths:#[[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section]]
withRowAnimation:UITableViewRowAnimationNone];
[self.tableView selectRowAtIndexPath:indexPath
animated:NO
scrollPosition:UITableViewScrollPositionNone];
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}
}else if (indexPath.row == 2) {
if ( show2 == NO) {
detailCell *cell = [self.tableView dequeueReusableCellWithIdentifier:#"detailCell3"forIndexPath:indexPath];
show2=YES;
cell.label.text = [self.array objectAtIndex:indexPath.row];
cell.image1.image = [UIImage imageNamed:[NSString stringWithFormat:[self.imageArray objectAtIndex:indexPath.row]]];
cell.imageButton.image = [UIImage imageNamed:#"Play_Symbol_copie_5#3x.png"];
NSArray *firstWords = [[self.carac objectAtIndex:pos] componentsSeparatedByString:#"\n"];
UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(0, 50, cell.frame.size.width , 100)];
[view1 setBackgroundColor:[UIColor colorWithRed:246/256.0 green:245/256.0 blue:241/256.0 alpha:1]];
[cell.contentView addSubview:view1];
caracLabel = 50;
for (int i = 0; i <firstWords.count; i++) {
NSArray *array = [[firstWords objectAtIndex:i]componentsSeparatedByString:#"/"];
UILabel *label = [[UILabel alloc]initWithFrame: CGRectMake(10, caracLabel, 90, 20)];
label.text = [array objectAtIndex:0];
label.textColor = [UIColor colorWithRed:150/256.0 green:150/256.0 blue:150/256.0 alpha:1];
label.numberOfLines = 0;
[label sizeToFit];
[cell.contentView addSubview:label];
UILabel *label1 = [[UILabel alloc]initWithFrame: CGRectMake(110, caracLabel, 205, 20)];
label1.text = [array objectAtIndex:1];
label1.textColor = [UIColor colorWithRed:150/256.0 green:150/256.0 blue:150/256.0 alpha:1];
label1.numberOfLines = 0;
[label1 sizeToFit];
caracLabel = caracLabel + label1.frame.size.height;
if (i != firstWords.count - 1) {
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, caracLabel, cell.frame.size.width, 1)];
[view setBackgroundColor:[UIColor whiteColor]];
caracLabel =caracLabel+2;
[cell.contentView addSubview:view];
}
[cell.contentView addSubview:label1];
}
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(100, 50, 1, caracLabel - 50)];
[view setBackgroundColor:[UIColor whiteColor]];
[cell.contentView addSubview:view];
view1.frame = CGRectMake(0, 50, cell.frame.size.width, caracLabel-50);
// [self.tableView reloadRowsAtIndexPaths:#[[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section]] withRowAnimation:UITableViewRowAnimationMiddle];
[self.tableView reloadRowsAtIndexPaths:#[[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section]]
withRowAnimation:UITableViewRowAnimationNone];
[self.tableView selectRowAtIndexPath:indexPath
animated:NO
scrollPosition:UITableViewScrollPositionNone];
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
} else {
detailCell *cell = [self.tableView dequeueReusableCellWithIdentifier:#"detailCell3"forIndexPath:indexPath];
show2= NO;
cell.label.text = [self.array objectAtIndex:indexPath.row];
cell.image1.image = [UIImage imageNamed:[NSString stringWithFormat:[self.imageArray objectAtIndex:indexPath.row]]];
cell.imageButton.image = [UIImage imageNamed:#"Play_Symbol_copie_2#3x.png"];
// [self.tableView reloadRowsAtIndexPaths:#[[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section]] withRowAnimation:UITableViewRowAnimationMiddle];
[self.tableView reloadRowsAtIndexPaths:#[[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section]]
withRowAnimation:UITableViewRowAnimationNone];
[self.tableView selectRowAtIndexPath:indexPath
animated:NO
scrollPosition:UITableViewScrollPositionNone];
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}
}else
if (indexPath.row == 3){
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[self.wiki objectAtIndex:pos]]];
UIWebView *video = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - +50)];
[video loadRequest:request];
video.delegate=self;
showWeb = YES;
UIActivityIndicatorView *actInd=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
actInd.color=[UIColor blackColor];
[actInd setCenter:self.view.center];
self.activityIndicator=actInd;
[self.view addSubview:video];
[video addSubview:self.activityIndicator];
}
}
This is how looking/work on simulator :
closed-
description-
caracteristics-
And this is how works for real device:
description-
caracteristics-
closed-
and
I don't know if that is problem, but row is changing colour after i press first time in real device. Why? Any ideas?
If everything working well in simulator but not in Device then check "dequeueReusableCellWithIdentifier"/"CellID" values because simulator is not case sensitive, but device is case sensitive.
It might be not find out your cell ID so it happen, I'm not sure about it but just check once.

UITableViewCell wrong height if is present only one item

I have a UITableView with a custom cell and at the beginning all is empty.
My UITableViewCell has a UITextView and when i tap on the screen i create a new cell and fire on it:
#import "MemoViewController.h"
#import "MemoViewCell.h"
#import "MemoModel.h"
static NSString *CellIdentifier = #"MemoCell";
#interface MemoViewController () <UITextViewDelegate>
#property (nonatomic, strong) MemoModel *model;
#property (nonatomic, strong) NSMutableDictionary *offscreenCells;
#end
#implementation MemoViewController
{
NSIndexPath *currentIndexPath;
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
self.model = [[MemoModel alloc] init];
//[self.model populateDataSource];
self.offscreenCells = [NSMutableDictionary dictionary];
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView registerClass:[MemoViewCell class] forCellReuseIdentifier:CellIdentifier];
self.tableView.rowHeight = UITableViewAutomaticDimension;
UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(insertNewRow:)];
gestureRecognizer.cancelsTouchesInView = NO;
[self.tableView addGestureRecognizer:gestureRecognizer];
currentIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
UIBarButtonItem *editButton = [[UIBarButtonItem alloc]
initWithTitle:#"Modifica"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(editButtonPressed:)];
self.navigationItem.rightBarButtonItem = editButton;
}
-(IBAction)editButtonPressed:(UIBarButtonItem *)sender
{
if ([sender.title isEqualToString:#"Fine"]) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[self.model.dataSource count] - 1 inSection:0];
MemoViewCell *cell = (MemoViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
[cell.bodyLabel resignFirstResponder];
}
}
-(void)insertNewRow:(UIGestureRecognizer *)gestureRecognizer
{
CGPoint point = [gestureRecognizer locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:point];
if (indexPath == nil) {
[self.model addObject];
[self.tableView reloadData];
indexPath = [NSIndexPath indexPathForRow:[self.model rowsCount] - 1 inSection:0];
}
[self.navigationItem.rightBarButtonItem setTitle:#"Fine"];
MemoViewCell *cell = (MemoViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
[cell.bodyLabel becomeFirstResponder];
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(contentSizeCategoryChanged:) name:UIContentSizeCategoryDidChangeNotification object:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void)contentSizeCategoryChanged:(NSNotification *)notification
{
[self.tableView reloadData];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.model.dataSource count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MemoViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if ([self.model.dataSource count] > 0) {
NSDictionary *dataSourceItem = [self.model.dataSource objectAtIndex:indexPath.row];
cell.bodyLabel.text = [dataSourceItem valueForKey:#"body"];
}
cell.bodyLabel.delegate = self;
[cell setNeedsUpdateConstraints];
[cell updateConstraintsIfNeeded];
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *reuserIdentifier = CellIdentifier;
if ([self.model.dataSource count] > 0) {
MemoViewCell *cell = [self.offscreenCells objectForKey:reuserIdentifier];
if (!cell) {
cell = [[MemoViewCell alloc] init];
[self.offscreenCells setObject:cell forKeyedSubscript:reuserIdentifier];
}
[cell updateFonts];
NSDictionary *dataSourceItem = [self.model.dataSource objectAtIndex:indexPath.row];
cell.bodyLabel.text = [dataSourceItem valueForKey:#"body"];
[cell setNeedsUpdateConstraints];
[cell updateConstraintsIfNeeded];
cell.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(tableView.bounds), CGRectGetHeight(cell.bounds));
[cell setNeedsLayout];
[cell layoutIfNeeded];
CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
height += 1;
CGFloat toReturn = height + [self measureHeightOfUITextView:cell.bodyLabel] - 30;
NSLog(#"Height for Row %li is %f", (long)indexPath.row, toReturn);
return toReturn;
} else {
return 44.0;
}
}
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 44.0;
}
/*
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
MemoViewCell *cell = (MemoViewCell *)[tableView cellForRowAtIndexPath:indexPath];
cell.bodyLabel.userInteractionEnabled = YES;
[cell.bodyLabel becomeFirstResponder];
}
*/
#pragma mark - Text View Delegate
- (void)textViewDidBeginEditing:(UITextView*)textView
{
MemoViewCell* cell = (MemoViewCell *)[self parentCellFor:textView];
if (cell)
{
NSIndexPath* indexPath = [self.tableView indexPathForCell:cell];
currentIndexPath = indexPath;
[self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}
}
/*
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
MemoViewCell *cell = (MemoViewCell *)[self.tableView cellForRowAtIndexPath:currentIndexPath];
[cell.bodyLabel becomeFirstResponder];
[self.tableView selectRowAtIndexPath:currentIndexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
return YES;
}
*/
- (UITableViewCell*)parentCellFor:(UIView*)view
{
if (!view)
return nil;
if ([view isMemberOfClass:[MemoViewCell class]])
return (UITableViewCell*)view;
return [self parentCellFor:view.superview];
}
-(void)textViewDidChange:(UITextView *)textView
{
NSMutableDictionary *dataSourceItem = [self.model.dataSource objectAtIndex:currentIndexPath.row];
[dataSourceItem setObject:textView.text forKey:#"body"];
[self.model.dataSource replaceObjectAtIndex:currentIndexPath.row withObject:dataSourceItem];
if ([textView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height != textView.frame.size.height) {
[self.tableView beginUpdates];
[self.tableView endUpdates];
}
}
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
return YES;
}
- (CGFloat)measureHeightOfUITextView:(UITextView *)textView
{
if ([textView respondsToSelector:#selector(snapshotViewAfterScreenUpdates:)])
{
CGRect frame = textView.bounds;
UIEdgeInsets textContainerInsets = textView.textContainerInset;
UIEdgeInsets contentInsets = textView.contentInset;
CGFloat leftRightPadding = textContainerInsets.left + textContainerInsets.right + textView.textContainer.lineFragmentPadding * 2 + contentInsets.left + contentInsets.right;
CGFloat topBottomPadding = textContainerInsets.top + textContainerInsets.bottom + contentInsets.top + contentInsets.bottom;
frame.size.width -= leftRightPadding;
frame.size.height -= topBottomPadding;
NSString *textToMeasure = textView.text;
if ([textToMeasure hasSuffix:#"\n"])
{
textToMeasure = [NSString stringWithFormat:#"%#-", textView.text];
}
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];
NSDictionary *attributes = #{ NSFontAttributeName: textView.font, NSParagraphStyleAttributeName : paragraphStyle };
CGRect size = [textToMeasure boundingRectWithSize:CGSizeMake(CGRectGetWidth(frame), MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
CGFloat measuredHeight = ceilf(CGRectGetHeight(size) + topBottomPadding);
return measuredHeight;
}
else
{
return textView.contentSize.height;
}
}
#end
With this code (insertNewRow:) i first create a new object on dataModel, i reload the data to setup all the table and next i make the first responder my last added UITextView.
On textViewDidChange: delegate i update the table to expand the row(s) to the UITextViewContent.
All works fine if i have at least 2 rows. If i have only one row, all rows assume all the same width.
If your cell's height is fixed then just use this method with return.
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
but if your cell's height is dynamic then you need to do some calculation and then return the correct height for the cell.

Flashing background on UITableview

I am trying to make quiz program. I used to UITableview for answers. How can i make to flashing on background when user click the correct answer? Is it possible?
Here is the some part of my project;
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row inSection:0]];
//cell=[[UITableViewCell alloc] initWithStyle:UITableViewStylePlain reuseIdentifier:#"Cell"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
NSNumber *rowNsNum = [NSNumber numberWithUnsignedInt:indexPath.row];
if ( [selectedCells containsObject:rowNsNum] )
{
//cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
NSString *text = [answers objectAtIndex:indexPath.row];
NSData *data = [text dataUsingEncoding: [NSString defaultCStringEncoding] ];
cell.textLabel.text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding ];
//cell.textLabel.text=[answers objectAtIndex:indexPath.row];
cell.textLabel.backgroundColor = [UIColor clearColor];
tableView.backgroundColor=[UIColor whiteColor];
cell.backgroundColor=[UIColor whiteColor];
[cell.textLabel setFont:[UIFont fontWithName:#"Helvatica" size:15]];
return cell;
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
CGRect rect = cell.frame;
UIView * view = [[UIView alloc] init];
UIImageView *back = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"ListGray"] ];
BOOL selx;
if (answerType==2)
selx = [self isSelected:indexPath];
else
selx = [lastIndexPath isEqual:indexPath];
if (selx) {
back = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"aaaa.png"] ];
cell.textLabel.textColor = [UIColor whiteColor];
[view addSubview:back];
cell.backgroundView = view;
back.frame = CGRectMake(0, 12,rect.size.width,rect.size.height-12);
} else {
cell.accessoryView = nil;
if (lastIndexPath != nil){
cell.textLabel.textColor = [UIColor blackColor];
[view addSubview:back];
cell.backgroundView = view;
back.frame = CGRectMake(0, 12,rect.size.width,rect.size.height-12);
back = nil;
}
}
[view addSubview:back];
cell.backgroundView = view;
back.frame = CGRectMake(0, 12,rect.size.width,rect.size.height-12);
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
tableView.allowsSelection = NO;
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSNumber *rowNsNum = [NSNumber numberWithUnsignedInt:indexPath.row];
if (answerType==3) {
NSString *secilenAnswerID;
secilenAnswerID= [genelAnswersID valueForKey:[answers objectAtIndex:indexPath.row]];
for (int a=0; a<[answers count]; a++) {
cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:a inSection:0]];
cell. accessoryType= UITableViewCellAccessoryNone;
[selectedCells removeObject:rowNsNum];
selectedCells=[[NSMutableArray alloc]init];
}
cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row inSection:0]];
isRadioSelected=TRUE;
radioAnswer = [genelAnswersID valueForKey:[answers objectAtIndex:indexPath.row]];
[selectedCells addObject:rowNsNum];
lastIndexPath = indexPath;
[tableView reloadData];
}
}
Sorry for my bad english. Thank you for your interest.
You can add a background view into your UITableViewCell with a backgroundColor. Then in your tableView: didSelectRowAtIndexPath: you can animate the hidden or alpha with the animation APIs in UIView. When the animation finishes you can animate hidden to TRUE or alpha back to 0 to get the flash effect.
Here is my question's solution. I took advice from Stephen Johnson:)
[UIView animateWithDuration:0.1f delay:0 options:(UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat) animations:^{
[UIView setAnimationRepeatCount:3];
cell.alpha = 0;
} completion: ^(BOOL finished) {
cell.hidden = YES;
[UIView animateWithDuration:0.1 animations:^{
cell.alpha = 1;
} completion: ^(BOOL finished) {
cell.hidden = NO;
}];
}];

Resources