Set UITableViewCell in full screen - ios

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.

Related

UITableView subview inside UITableViewCell won't display

I'm trying to create a UITableview, where each cell contains another UITableView. It's basically a list of 2-3 rows, where each row then has a sublist of 2-3 rows inside.
The main ViewController behaves just like any other TableViewController, and inside the cellForRowAtIndexPath, it attempts to add a SubTableViewController.view with a dynamic height. The SubTableViewController is the second tableview and each has their own Datasource.
The problem I'm running into is the SubTableViewController appears to render properly using the debugger, with the correct data and number of cells, but it simply isn't appearing when rendering. I noticed it has a contentSize height of "0" in its ViewDidAppear, despite having 2+ rows produced with height. The project uses AutoLayout but the SubTableViewController's frame is set programmatically when added.
Any ideas what I can do to get something to appear here?
Structure of Data (periods are the subTable)
[{name:"activity 1",
periods:[{name:"period1",desc:"desc1"},
{name:"period2",desc:"desc2"},
{name:"period3",desc:"desc3"}
]
},
{name:"activity 2",
periods:[{name:"period1",desc:"desc1"},
{name:"period2",desc:"desc2"},
{name:"period3",desc:"desc3"}
]
}]
ViewController
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_data count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
UIImageView *imageView = (UIImageView*)[cell viewWithTag:1];
UIView *subTableView = (UIView*)[cell viewWithTag:3];
return imageView.frame.size.height + subTableView.frame.size.height + 20;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = #"tableViewCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
ActivityModel *model = _data[indexPath.row];
UILabel *nameLabel = (UILabel*)[cell viewWithTag:2];
nameLabel.text = model.name;
UIView *internalView = (UIView*)[cell viewWithTag:10];
SubTableViewController *subTableViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"SubTableViewController"];
subTableViewController.activityModel = model;
subTableViewController.view.tag = 3;
subTableViewController.view.frame = CGRectMake(0,
60,
internalView.frame.size.width,
subTableViewController.view.frame.size.height);
[internalView addSubview:subTableViewController.view];
[internalView bringSubviewToFront:subTableViewController.view];
[subTableViewController.tableView reloadData];
return cell;
}
SubTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
int height = 0;
for (int section = 0; section < [self numberOfSectionsInTableView:_tableView]; section++){
for(int row = 0; row < [self tableView:_tableView numberOfRowsInSection:section]; row++){
height += [self tableView:_tableView heightForRowAtIndexPath:[NSIndexPath indexPathForItem:row inSection:section]];
}
}
CGRect tableFrame = self.tableView.frame;
tableFrame.size.height = height;
self.tableView.frame = tableFrame;
CGRect viewFrame = self.view.frame;
viewFrame.size.height = height;
self.view.frame = viewFrame;
[self.view bringSubviewToFront:_tableView];
// [self.tableView layoutIfNeeded];
// [self.tableView setNeedsDisplay];
// [self.tableView reloadData];
// _tableView.contentSize = CGSizeMake(600, 52);
self.view.backgroundColor = [UIColor redColor];
self.tableView.backgroundColor = [UIColor blueColor];
self.tableView.hidden = NO;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [_activityModel.periods count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
UILabel *nameLabel = (UILabel*)[cell viewWithTag:3];
UITextView *textView = (UITextView*)[cell viewWithTag:5];
float textViewHeight = [textView.text sizeWithFont:[UIFont systemFontOfSize:13] constrainedToSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - 40, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping].height;
return nameLabel.frame.size.height + textViewHeight + 20;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"tableViewCell"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
PeriodModel *model = _activityModel.periods[indexPath.row];
UILabel *nameLabel = (UILabel*)[cell viewWithTag:3];
UILabel *durationLabel = (UILabel*)[cell viewWithTag:4];
UITextView *textView = (UITextView*)[cell viewWithTag:5];
nameLabel.text = model.name;
durationLabel.text = [NSString stringWithFormat:#"%d minutes", (int)(model.durationSeconds/60)];
textView.text = model.description;
textView.textContainerInset = UIEdgeInsetsZero;
textView.textContainer.lineFragmentPadding = 0;
textView.scrollEnabled = NO;
CGRect frame = textView.frame;
frame.size.height = [textView.text sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:CGSizeMake(cell.contentView.frame.size.width, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping].height;
textView.frame = frame;
return cell;
}
Simulator Image. The title is the outer UITableCell, and below it in red is the added SubTableViewController.view. The UITableView should cover the red, but is not appearing at all here. It is not hidden, underneath, etc.
Do not put a table view inside your cells.
There is little benefit to doing this for your described use. Use sections and rows. Each section would be your current cell. And each row in that section would be a row from your current embedded table view.
Further, if your internal table views had differing sizes you would be needing to calculate all of the internal cell heights for each external cell. That is exactly what happens with sections and rows, but you as the developer only need to worry about the rows and UITableView will handle the section sizing.

Add Storyboard UITableView and custom UITableViewCells to UIScrollView programmatically

In my Storboard, I have a UIViewController (ParentClass) -> UIScrollView (linked to Parent) -> UITableView (linked to Parent) -> UITableViewCell (2 cells, each with their own Class).
What I'm trying to do is add several instances of the UITableView (with the custom cells) into the UIScrollView.
I am close with the following code, but the cells are coming up empty:
self._scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
self._scrollView.pagingEnabled = YES;
self._scrollView.showsVerticalScrollIndicator = NO;
self._scrollView.alwaysBounceVertical = NO;
NSInteger numberOfViews = 22;
for (int i = 0; i < numberOfViews; i++) {
CGFloat xOrigin = i * self.view.frame.size.width;
UITableViewController *theTableView = [[UITableViewController alloc] initWithStyle:UITableViewStyleGrouped];
theTableView.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
theTableView.tableView.frame = CGRectMake(xOrigin, 0, self.view.frame.size.width, self._scrollView.frame.size.height);
theTableView.tableView.backgroundColor = [UIColor colorWithRed:246/255.0 green:248/255.0 blue:249/255.0 alpha:1];
theTableView.tableView.delegate = self;
theTableView.tableView.dataSource = self;
theTableView.tableView.tag = 100+i;
[self._scrollView addSubview:theTableView.tableView];
}
self._scrollView.contentSize = CGSizeMake(self.view.frame.size.width * numberOfViews, self.view.frame.size.height);
[self.view addSubview:self._scrollView];
All the tables show up and all the pages are there and the scroll as they should, but the Custom Cell layouts are not showing up.
Here's the code I use to layout the tables:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 5;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 2;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if ([indexPath row] == 0) {
return 127.0;
} else {
return 56.0;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == 0) {
static NSString *CellIdentifier = #"MealImageCell";
MealImageCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[MealImageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
[self configureImageCell:cell atIndexPath:indexPath];
return cell;
} else {
static NSString *CellIdentifier = #"MealInfoCell";
MealInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[MealInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
[self configureInfoCell:cell atIndexPath:indexPath];
return cell;
}
}
- (void)configureImageCell:(MealImageCell *)cell atIndexPath:(NSIndexPath *)indexPath {
NSMutableDictionary *dictMeal = [[NSMutableDictionary alloc] init];
if ([arrayMeals count]) {
dictMeal = [arrayMeals objectAtIndex:indexPath.section];
cell.userInteractionEnabled = YES;
} else {
cell.userInteractionEnabled = NO;
}
[cell.imageFood sd_setImageWithURL:[NSURL URLWithString:[dictMeal valueForKey:#"img_src"]]
placeholderImage:[UIImage imageNamed:[NSString stringWithFormat:#"meal%li.jpeg",(long) indexPath.section+1]]];
}
- (void)configureInfoCell:(MealInfoCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
NSString *mealName;
if ([arrayMeals count]) {
NSMutableDictionary *dictMeal = [arrayMeals objectAtIndex:indexPath.section];
cell.userInteractionEnabled = YES;
if ([dictMeal valueForKey:#"mealDescription"] == [NSNull null]) {
mealName = NSLocalizedString(#"No Name", nil);
} else if ([[dictMeal valueForKey:#"mealDescription"] isEqualToString:#""]) {
mealName = NSLocalizedString(#"Deleted", nil);
} else {
mealName = [decodeHTMLEntities decodeHTMLEntities:[[dictMeal valueForKey:#"mealDescription"] stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
}
} else {
cell.userInteractionEnabled = NO;
mealName = NSLocalizedString(#"Loaing Meal...", nil);
}
cell.labelFood.text = mealName;
}
Without the scrollView, the table is populated as it should be.
The answer is to relace:
MealImageCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
with
MealImageCell *cell = [_myTablView dequeueReusableCellWithIdentifier:CellIdentifier];
with _myTableView being the IBOutlet for the table view in Storyboard.

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.

UiCollectionViewCell random images flipping

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]];
}

how to change image when clicked on tableview cell iphone

i have a tableview. i add image to the cells when clicked on the cell in didselectrow method by using cell.conteview addsubview. but the problem is if i click on 1st cell it changes the image and when i click on another cell image will appears but the old image is not removed from the previous cell. This is happening for all cells in table view if a cell is clicked.
i used the code as follows
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
Practices *bPractices = [topics objectAtIndex:indexPath.row];
UIImageView *clickView;
//[cell.contentView removeFromSuperview];
clickView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 315, 82)];
clickView.image = [UIImage imageNamed:#"list_bg_hover.png"];
[cell.contentView addSubview:clickView];
[clickView release];
UILabel *labelText= [[UILabel alloc]initWithFrame:CGRectMake(90, 30, 320, 20)];
labelText.text=bPractices.practices_title;
labelText.backgroundColor=[UIColor clearColor];
[cell.contentView addSubview:labelText];
}
pls help me how to solve this issue
Thanks in advance
I did something similar, but not with images but buttons. If a cell wasn't selected yet and gets tabbed, the size is changed and a certain and individual number of buttons is added. If another cell was selected, this one gets closed.
Code from form the UITableViewController
interface:
int openedCellIndex;//<-what cell is selected
int buttonCounter;
implementation:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ( indexPath.row != openedCellIndex )
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[TRTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier]
autorelease];
//cell.frame = CGRectMake (0,0, 320, 100);
}
id <P_E_P1Article> article = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = article.name;
if ( self.cellBackgroundColor )
cell.backgroundColor = self.cellBackgroundColor;
return cell;
}
else {
//get article
id <P_E_P1Article> article = [self.fetchedResultsController objectAtIndexPath:indexPath];
//number of buttons
int buttons = [article.specification count];
int height = 50 * ceil(buttons / 2) + 50;
//construct special cell
UITableViewCell *cell = [[[TRTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"CellBig"]
autorelease];
cell.frame = CGRectMake (0,0, 320, 150);
cell.textLabel.text = #"";
//add label
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 280, 30)];
label.font = [UIFont boldSystemFontOfSize:17];
label.text = article.name;
label.backgroundColor = [UIColor clearColor];
[cell addSubview:label];
[label release];
if ( buttonMapper == nil )
self.buttonMapper = [NSMutableDictionary dictionaryWithCapacity:10];
//NSLog (#" bla: %#", article.isFreePrice);
//see if we have a free prized article
//create the buttons
NSEnumerator *enumerator = [article.specification objectEnumerator];
id <P_E_P1ArticleSpecification> spec;
int count = 0;
NSArray *specs =
[self sortedArticleSpecifications:article];
for ( spec in specs ) {
//see which row and col the button is in
int row = floor ( count / 2 );
int col = count % 2;
//define button position
int left = 20 + col * 145;
int top = 45 + row * 50;
//create button
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(left, top, 135, 40);
[cell addSubview:button];
[button setTitleColor:[UIColor blackColor] forState:0];
[button addTarget:self
action:#selector(buttonTapped:)
forControlEvents:UIControlEventTouchUpInside];
//remember which article the button is attached to
buttonCounter++;
button.tag = buttonCounter;
[buttonMapper setValue:spec forKey:[NSString stringWithFormat:#"bla%d",buttonCounter]];
count++;
}
if ( self.cellBackgroundColor )
cell.backgroundColor = self.cellBackgroundColor;
return cell;
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ( openedCellIndex == indexPath.row )
{
id <P_E_P1Article> article = [self.fetchedResultsController objectAtIndexPath:indexPath];
int count = [article.specification count];
int height = 50 * ceil(count / 2.) + 50;
return height;
}
return 50;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[self openRow:indexPath.row];
[self.searchBar resignFirstResponder];
}
- (void) openRow:(int) index
{
if ( index == openedCellIndex ) return;
int oldIndex = openedCellIndex;
openedCellIndex = index;
NSUInteger indexArr[] = {0, oldIndex};
NSIndexPath *oldPath = [NSIndexPath indexPathWithIndexes:indexArr length:2];
NSUInteger indexArr2[] = {0, openedCellIndex};
NSIndexPath *newPath = [NSIndexPath indexPathWithIndexes:indexArr2 length:2];
//update view
[(UITableView *)self.view beginUpdates];
if ( oldIndex >= 0 )
[(UITableView *)self.view reloadRowsAtIndexPaths:[NSArray arrayWithObject:oldPath]
withRowAnimation:UITableViewRowAnimationFade];
if (openedCellIndex >=0 )
[(UITableView *)self.view reloadRowsAtIndexPaths:[NSArray arrayWithObject:newPath]
withRowAnimation:UITableViewRowAnimationFade];
[(UITableView *)self.view endUpdates];
}
You could also subclass UITableViewCell and handle the select/deselect process in the setSelected method. Then use your custom cell as the type for the prototype cell instead of the default.

Resources