I am trying to create something like this here.
Here is the sample code which I tried:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"RefundMeCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
cell.selectionStyle=UITableViewCellSelectionStyleNone;
}
UIImageView *rowImageView=(UIImageView*)[cell viewWithTag:1];
UILabel *questionOptionLabel=(UILabel*)[cell viewWithTag:2];
UIImageView *collapseImageView=(UIImageView*)[cell viewWithTag:3];
UIScrollView *scrollView=(UIScrollView*)[cell viewWithTag:4];
UIImageView *sampleImageView=(UIImageView*)[cell viewWithTag:5];
UIButton *sampleButton=(UIButton*)[cell viewWithTag:6];
UILabel *instructionHeaderLabel=(UILabel*)[cell viewWithTag:7];
UILabel *instructionsLabel=(UILabel*)[cell viewWithTag:8];
UIPageControl *pgCntrl=(UIPageControl*)[cell viewWithTag:9];
[rowImageView setImage:[UIImage imageNamed:#"normalcell.png"]];
questionOptionLabel.text = #"";
collapseImageView.image = nil;
scrollView.hidden = YES;
sampleImageView.image = nil;sampleImageView.hidden = YES;
sampleButton.hidden = YES;
instructionHeaderLabel.text = #"";instructionHeaderLabel.hidden = YES;
instructionsLabel.text = #"";instructionsLabel.hidden = YES;
pgCntrl.hidden = YES;
[sampleButton addTarget:self action:#selector(userImageButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
sampleImageView.image = nil;
[collapseImageView setImage:[UIImage imageNamed:#"down.png"]];
questionOptionLabel.text=#"";
instructionHeaderLabel.text=#"Instructions";
if (indexPath.row == 0)
{
instructionHeaderLabel.hidden = NO;
sampleImageView.image = self.barcodeImage;
scrollView.hidden = NO;
scrollView.delegate = self;
pgCntrl.hidden = NO;
sampleImageView.hidden = NO;
sampleButton.hidden = NO;
pgCntrl.numberOfPages = 5;
pgCntrl.currentPage = 0;
for (int i = 0; i<5; i++)
{
[scrollView addSubview:sampleImageView];
[scrollView addSubview:sampleButton];
}
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * 5, scrollView.frame.size.height);
}
else
{
instructionHeaderLabel.hidden = NO;
sampleImageView.image = nil;
scrollView.hidden = NO;
scrollView.delegate = self;
pgCntrl.hidden = NO;
sampleImageView.hidden = NO;
sampleButton.hidden = NO;
pgCntrl.numberOfPages = 3;
pgCntrl.currentPage = 0;
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * 3, scrollView.frame.size.height);
}
return cell;
}
My problem is, how I can add UIImageView, UILabel, etc when UIScrollView is scrolled to second page?
It should look like this
Currently UIImageView, UILabel is shown only first time. when I scroll to second page, UIImageView and UILabel scroll back and nothing is shown on second page.
Here is my code
- (void)viewDidLoad
{
[super viewDidLoad];
tableObj.dataSource = self;
tableObj.delegate = self;
scrollView.delegate = self;
// customObj = [[customCellForText alloc]init];
imageArray = [[NSMutableArray alloc]initWithObjects:[UIImage imageNamed:#"image1.jpg"],
[UIImage imageNamed:#"image2.jpg"],
[UIImage imageNamed:#"man-actor-Ashton-Kutcher-Wallpaper.jpg"],
[UIImage imageNamed:#"Man-Booker-Prize-judges-p-011.jpg"],
[UIImage imageNamed:#"man-curl.jpg"]
,nil];
// pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(170, 180, 100, 30)];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 5;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifier = #"cell";
customCellForText *cell = [tableObj dequeueReusableCellWithIdentifier:cellIdentifier];
NSArray *nib = [[NSBundle mainBundle]loadNibNamed:#"customCellForText" owner:self options:nil];
cell = [nib objectAtIndex:0];
scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(130, 80, 150, 100)];
scrollView.pagingEnabled = YES;
scrollView.delegate = self;
[scrollView setShowsHorizontalScrollIndicator:NO];
//[scrollView setShowsVerticalScrollIndicator:NO];
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * imageArray.count, self.scrollView.frame.size.height);
[cell.contentView addSubview:scrollView];
for (int i = 0; i < imageArray.count; i++){
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * i;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
subview = [[UIImageView alloc] initWithFrame:frame];
subview.image = [imageArray objectAtIndex:i];
subview.contentMode = UIViewContentModeScaleAspectFit;
[self.scrollView addSubview:subview];
}
pageControl = [[UIPageControl alloc]init];
pageControl.frame = CGRectMake(170, 180, 100, 30);
pageControl.numberOfPages = imageArray.count;
pageControl.currentPage = 0;
pageControl.hidesForSinglePage = YES;
[cell.contentView addSubview:pageControl];
[pageControl addTarget:self action:#selector(changePage:) forControlEvents:UIControlEventValueChanged];
cell.nameLabel.text=#"amol";
return cell;
}
- (void)scrollViewDidScroll:(UIScrollView *)sender{
CGFloat pageWidth = sender.frame.size.width;
int newPage = floor((sender.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
self.pageControl.currentPage = newPage;
}
I would recommend you to use a different approach because your solution is not scalable. If you want n pages you'll have to add n images & label to your scroll view which will be a mess and also not memory efficient.
Give a look at this library I think it will suit your need.
Related
My problem is that there is this ugly white space that is appearing at the bottom of my UITableView.
The only way to get the cell divider line thing (whatever it is called) is to scroll all the way to the bottom and back up, then it will appear.
But even when it appears, there is still a massive area of white space below my last cell.
Here is my two images to illustrate my problem.
Here is my code:
Post *currentPost;
#interface CommentViewController ()
#end
#implementation CommentViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor colorWithRed:(255/255.0) green:(221/255.0) blue:(85/255.0) alpha:1.0f]];
[self.leftLabel setBackgroundColor:[UIColor colorWithRed:(255/255.0) green:(221/255.0) blue:(85/255.0) alpha:1.0f]];
[self.rightLabel setBackgroundColor:[UIColor colorWithRed:(255/255.0) green:(221/255.0) blue:(85/255.0) alpha:1.0f]];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://kmjt.org/getComments.php"]];
NSData *data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
postArray = [[NSMutableArray alloc] init];
for(int i = 0; i < jsonArray.count; i++)
{
NSString *nickname = [[jsonArray objectAtIndex:i] objectForKey:#"nickname"];
NSString *squeal = [[jsonArray objectAtIndex:i] objectForKey:#"comment"];
NSString *timeSincePosted = [[jsonArray objectAtIndex:i] objectForKey:#"TIME_TO_SEC(TIMEDIFF(NOW( ), c.timePosted))"];
[postArray addObject:[[Post alloc] initWithNickname:nickname andSqueal:squeal andTimeSincePosted:timeSincePosted]];
}
viewArray = [[NSMutableArray alloc] init];
UILabel *nicknameLabelMainPost = [[UILabel alloc]initWithFrame:CGRectMake(43, 5, 320-10, 30)];
nicknameLabelMainPost.backgroundColor = [UIColor clearColor];
nicknameLabelMainPost.text = currentPost.nickname;
nicknameLabelMainPost.font = [UIFont boldSystemFontOfSize:20];
UITextView *textViewMainPost = [[UITextView alloc] initWithFrame:CGRectMake(38, 22, 320-34, 0)];
textViewMainPost.backgroundColor = [UIColor clearColor];
textViewMainPost.font = [UIFont systemFontOfSize:15];
textViewMainPost.text = currentPost.squeal;
[textViewMainPost sizeToFit];
[textViewMainPost layoutIfNeeded];
textViewMainPost.userInteractionEnabled = NO;
UILabel *timePostedLabelMainPost = [[UILabel alloc]initWithFrame:CGRectMake(43, 50+textViewMainPost.contentSize.height-20, 320-10, 15)];
timePostedLabelMainPost.backgroundColor = [UIColor clearColor];
timePostedLabelMainPost.text = [self getTimeSincePostedLabel:currentPost.timeSincePosted];
timePostedLabelMainPost.textColor = [UIColor colorWithRed:(181/255.0) green:(181/255.0) blue:(189/255.0) alpha:1.0f];
timePostedLabelMainPost.font = [UIFont boldSystemFontOfSize:15];
UIView *view = [[UIView alloc] initWithFrame: CGRectMake (0, 0, 320, 30+textViewMainPost.frame.size.height)]; // 30 is nickname label height, 20 is time posted label height
[view addSubview:nicknameLabelMainPost];
[view addSubview:textViewMainPost];
[view addSubview:timePostedLabelMainPost];
[viewArray addObject:view];
for(int i = 0; i < postArray.count; i++)
{
Post *postObject;
postObject = [postArray objectAtIndex:i];
UILabel *nicknameLabel = [[UILabel alloc]initWithFrame:CGRectMake(75, 5, 320-65, 30)];
nicknameLabel.backgroundColor = [UIColor clearColor];
nicknameLabel.text = postObject.nickname;
nicknameLabel.font = [UIFont boldSystemFontOfSize:15];
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(70, 22, 320-65, 0)];
textView.backgroundColor = [UIColor clearColor];
textView.font = [UIFont systemFontOfSize:10];
textView.text = postObject.squeal;
[textView sizeToFit];
[textView layoutIfNeeded];
textView.userInteractionEnabled = NO;
UILabel *timePostedLabel = [[UILabel alloc]initWithFrame:CGRectMake(75, 50+textView.contentSize.height-20, 320-65, 15)];
timePostedLabel.backgroundColor = [UIColor clearColor];
timePostedLabel.text = [self getTimeSincePostedLabel:postObject.timeSincePosted];
timePostedLabel.textColor = [UIColor colorWithRed:(181/255.0) green:(181/255.0) blue:(189/255.0) alpha:1.0f];
timePostedLabel.font = [UIFont boldSystemFontOfSize:15];
UIView *view = [[UIView alloc] initWithFrame: CGRectMake (0, 0, 320, 30+textView.frame.size.height+20-20+2)]; // 30 is nickname label height, 20 is time posted label height
[view addSubview:nicknameLabel];
[view addSubview:textView];
[view addSubview:timePostedLabel];
[viewArray addObject:view];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"%i", viewArray.count); // This is returning 3 (the correct amount of rows)
return viewArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
else
[[cell.contentView subviews] makeObjectsPerformSelector:#selector(removeFromSuperview)];
[cell.contentView addSubview:[viewArray objectAtIndex:indexPath.row]];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 0;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIView *view = [viewArray objectAtIndex:indexPath.row];
return view.frame.size.height+30;
}
- (NSString *)getTimeSincePostedLabel:(NSString *)secondsString
{
int num_seconds = [secondsString integerValue];
int days = num_seconds / (60 * 60 * 24);
num_seconds -= days * (60 * 60 * 24);
int hours = num_seconds / (60 * 60);
num_seconds -= hours * (60 * 60);
int minutes = num_seconds / 60;
if(days > 0)
return [NSString stringWithFormat:#"%i d", days];
else if(hours > 0)
return [NSString stringWithFormat:#"%i h", hours];
else if(minutes > 0)
return [NSString stringWithFormat:#"%i m", minutes];
return [NSString stringWithFormat:#"%i s", num_seconds];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
i think its the problem with your heightForRowAtIndexPath,every time you increasing view height by 30,try this
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIView *view = [viewArray objectAtIndex:indexPath.row];
CGFloat cellHeight = view.frame.size.height;
return cellHeight+30;
}
Something weird going on here. I have a tableview, and in each row there is a segmentedcontrol. The meaning of this is, that there only has to be one segmented control selected at all time. On a click of a 'control item', there is a segue that is pushed.
If I constantly select items of different segmented controls, there is nothing going on, my code works perfectly. When i select an different item from the same segmented control, i have this error:
nested push animation can result in corrupted navigation bar
Finishing up a navigation transition in an unexpected state. Navigation Bar subview tree might get corrupted.
Unbalanced calls to begin/end appearance transitions for .
This is my code:
#interface PerformancesController ()
{
GFilm* currentFilm;
GTimePerformance* chosenTimePerf;
}
#end
#implementation PerformancesController
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [currentFilm.dayList count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"myCustomCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"myCustomCell"];
}
CAGradientLayer *bgLayer = [BackgroundLayer blackGradient];
bgLayer.frame = cell.bounds;
[cell.contentView.layer addSublayer:bgLayer];
cell.contentView.backgroundColor = [UIColor darkGrayColor];
cell.textLabel.textAlignment = UITextAlignmentLeft;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
if(indexPath.row == 0)
{
CGRect rctStreep = cell.bounds;
rctStreep.origin.y = rctStreep.origin.y+1;
rctStreep.size.height = 1;
UIImageView* imgv = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"streep.png"]];
imgv.backgroundColor = [UIColor blackColor];
imgv.frame = rctStreep;
[cell.contentView addSubview:imgv];
}
CGRect rctStreep = cell.bounds;
rctStreep.origin.y = rctStreep.origin.y + rctStreep.size.height;
rctStreep.size.height = 1;
UIImageView* imgv = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"streep.png"]];
imgv.backgroundColor = [UIColor blackColor];
imgv.frame = rctStreep;
[cell.contentView addSubview:imgv];
imgv = nil;
NSArray* dayList = currentFilm.dayList;
GDay* d = (GDay*)[dayList objectAtIndex:indexPath.row];
CGRect rctDayLabel = CGRectMake(15, 7, 80, 30);
UILabel* lblDay = [[UILabel alloc]initWithFrame:rctDayLabel];
lblDay.textColor = [GColor yellowAccentColor];
NSDate* date = d.date;
if([date isToday])
{
lblDay.text = #"Vandaag";
}
else if([date isTomorrow])
{
lblDay.text = #"Morgen";
}
else
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd/MM"];
lblDay.text = [formatter stringFromDate:date];
}
[cell.contentView addSubview:lblDay];
NSMutableArray* itemArray = [[NSMutableArray alloc]init];
int i = 0;
GTimePerformance* prevChosen = currentFilm.displayPerformance;
int gekozen = -1;
for(i; i < [d.timeIdList count]; i++)
{
GTimePerformance* per = [d.timeIdList objectAtIndex:i];
if([per.performanceId isEqualToString:prevChosen.performanceId])
{
gekozen = i;
}
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm"];
[itemArray addObject:[formatter stringFromDate:per.performanceTime]];
}
float itemWidth = (cell.frame.size.width - (2* rctDayLabel.origin.x))/4;
MySegmentedControl *segmentedControl = [[MySegmentedControl alloc] initWithItems:itemArray];
segmentedControl.frame = CGRectMake(rctDayLabel.origin.x, cell.frame.size.height - rctDayLabel.origin.y - 30, itemWidth*[d.timeIdList count] , 30);
segmentedControl.segmentedControlStyle = UISegmentedControlStylePlain;
segmentedControl.tintColor = [GColor filterComponentColor];
if(gekozen >= 0)
{
[segmentedControl setSelectedSegmentIndex:gekozen];
}
[segmentedControl addTarget:self
action:#selector(clickedPerformance:)
forControlEvents:UIControlEventValueChanged];
UIFont *font = [UIFont systemFontOfSize:10.0f];
NSDictionary *attributes = [NSDictionary dictionaryWithObject:font
forKey:NSFontAttributeName];
[segmentedControl setTitleTextAttributes:attributes
forState:UIControlStateNormal];
segmentedControl.tag = 200 + indexPath.row;
[cell.contentView addSubview:segmentedControl];
return cell;
}
-(void)clickedPerformance:(id)sender
{
UISegmentedControl *segment = (UISegmentedControl*)sender;
if(segment.selectedSegmentIndex != -1)
{
int tag = segment.tag;
int i = 0;
for(i; i < [currentFilm.dayList count]; i++)
{
int diffTag = i + 200;
if(diffTag != tag)
{
UISegmentedControl* sControl = (UISegmentedControl*)[self.view viewWithTag:diffTag];
[sControl setSelectedSegmentIndex:UISegmentedControlNoSegment];
}
}
NSLog(#"lalala");
GDay* day = (GDay*)[currentFilm.dayList objectAtIndex:tag-200];
chosenTimePerf = [day.timeIdList objectAtIndex:segment.selectedSegmentIndex];
NSLog(chosenTimePerf.performanceId);
[self performSelector:#selector(goSegue) withObject:nil afterDelay:0.35];
}
}
-(void)goSegue
{
[self performSegueWithIdentifier:#"pushPrices" sender:self];
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
NSString * segueName = segue.identifier;
if ([segueName isEqualToString: #"pushPrices"]) {
PricesController* pc = (PricesController*)[segue destinationViewController];
[pc setMovie:currentFilm andPerformance:chosenTimePerf];
}
}
#end
Why do you delay the goSegue method? hitting the item multiple times before afterDelay has elapsed will cause trouble.
I would change:
[self performSelector:#selector(goSegue) withObject:nil afterDelay:0.35];
to:
[self goSegue];
I am trying to add a label (string array) from Parse.com into a subview that shows up after tapping an image inside a UICollectionViewCell.
The subview appears, and the text also but it's the same text in every subview of each cell. It is not changing..
The arrays in my dataBrowser are: precio_0, precio_1, precio_2 etc..
What am I doing wrong? How would the code go to recognize it is another cell. If I set the code in the UICollectionViewCell and not in the Subview there is no problem, the text changes in every view. So I'm missing something but don't know what it is.
**NOTE: This is the DetailView and the data is being passed as a property so to get the data the method goes: [self.vestimenta objectForKey:#"String"]
My code:
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"Cell";
VestimentaDetailCell *cell = (VestimentaDetailCell *) [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
[cell.activityIndicator startAnimating];
cell.imageFile.image = [UIImage imageNamed:#"LoadLook.png"];
PFFile *imageFile = [self.vestimenta objectForKey:[NSString stringWithFormat:#"image_%ld", (long)indexPath.row]];
[imageFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (!error && data.length > 0) {
cell.imageFile.image = [UIImage imageWithData:data];
UITapGestureRecognizer *infoLook = [[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(handleTap:)];
infoLook.numberOfTapsRequired = 1;
[cell.imageFile addGestureRecognizer:infoLook];
} else {
[cell.progressView removeFromSuperview];
}
} progressBlock:^(int percentDone) {
float percent = percentDone * 0.02;
[cell.progressView setProgress:percent];
if (percentDone == 100){
[cell.progressView removeFromSuperview];
};
[cell.showInfo addTarget:self
action:#selector(handleTap:)
forControlEvents:UIControlEventTouchUpInside];
[cell.activityIndicator stopAnimating];
}];
return cell;
}
-(void)handleTap:(UITapGestureRecognizer *) infoLook{
CGRect frame = CGRectMake(0, 0, 320, 519);
UIView *infoView = [[UIView alloc] initWithFrame:frame];
infoView.opaque = NO;
infoView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.8f];
infoView.userInteractionEnabled = YES;
infoView.tag = 01;
UIButton *priceTag = [[UIButton alloc] initWithFrame:CGRectMake(282, 370, 25, 25)];
[priceTag setImage:[UIImage imageNamed:#"Price.png"] forState:UIControlStateNormal];
UILabel *precioProductos = [[UILabel alloc] initWithFrame:CGRectMake(32, 370, 240, 190)];
precioProductos.textColor = [UIColor whiteColor];
precioProductos.backgroundColor = [UIColor clearColor];
precioProductos.textAlignment = NSTextAlignmentRight;
precioProductos.numberOfLines = 0;
precioProductos.font = [UIFont fontWithName:#"HelveticaNeue-LightItalic" size:15];
This part shows the calling of the arrays in Parse.com:
VestimentaDetailCell *price = (VestimentaDetailCell *)[precioProductos superview];
NSIndexPath *indexPath = [imagesCollection indexPathForCell:price];
NSMutableString *precio = [NSMutableString string];
for (NSString* precios in [self.vestimenta objectForKey:[NSString stringWithFormat:#"precios_%ld", (long)indexPath.row]]) {
[precio appendFormat:#"%#\n", precios];
}
precioProductos.text = precio;
[precioProductos sizeToFit];
CGRect myFrame = precioProductos.frame;
myFrame = CGRectMake(myFrame.origin.x, myFrame.origin.y, 240, myFrame.size.height);
precioProductos.frame = myFrame;
[infoView addSubview:priceTag];
[infoView addSubview:precioProductos];
[self.view addSubview:infoView];
UITapGestureRecognizer *dismissView = [[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(processTap:)];
dismissView.numberOfTapsRequired = 1;
[infoView addGestureRecognizer:dismissView];
}
I have created an app with a table view. Which uses a view and a label in each cell. But if I create the views and cells in the (!cell) code it returns empty cells and if I remove the (!cell) condition it displays the data but does not take dynamic height. Can anyone please help me.
- (void)viewDidLoad{
NSString *Path = [[NSBundle mainBundle] bundlePath];
NSString *DataPath = [Path stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.plist", LanguageFile]];
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] initWithContentsOfFile:DataPath];
self.reloadArray = [tempDict objectForKey:#"Rows"];}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [self.reloadArray count];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// Get data for the current row
NSString *textData = [reloadArray objectAtIndex:indexPath.section]
CGFloat dataTextHeight = [self getLabelHeightForIndex:textData];
if(dataTextHeight < 44)
{
dataTextHeight = 44;
}
return dataTextHeight;
}
-(CGFloat)getLabelHeightForIndex:(NSString *)string
{
CGSize maximumSize = CGSizeMake(280, 10000);
CGSize labelHeightSize = [string sizeWithFont:[UIFont fontWithName:#"Helvetica" size:14.0f] constrainedToSize:maximumSize lineBreakMode:NSLineBreakByWordWrapping];
if(labelHeightSize.height < 44){
labelHeightSize.height = 44;
}
return labelHeightSize.height;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Cell";
static const int textViewTag = 1, textLabelTag = 2;
UIImageView *img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"standard_back.png"]];
img.frame = tableView.frame;
tableView.backgroundView = img;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
// First view
UIView *textView = [[UIView alloc] initWithFrame: CGRectMake(0.0, 0.0, 280.0, 36.00)];
textView.tag = textViewTag;
textView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[cell.contentView addSubview:textView];
// First label
UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 0.0, 270.0, 36.00)];
textLabel.tag = textLabelTag;
textLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size:14.0f];
textLabel.textColor = [UIColor whiteColor];
textLabel.backgroundColor = [UIColor clearColor];
textLabel.numberOfLines = 0;
textLabel.lineBreakMode = NSLineBreakByWordWrapping;
textLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
// textLabel.clipsToBounds = YES;
[cell.contentView addSubview:textLabel];
}
NSString *textData = [reloadArray objectAtIndex:(indexPath.section)];
CGFloat dataTextHeight = [self getLabelHeightForIndex:textData];
UIView *textView = [cell.contentView viewWithTag:textViewTag];
CGRect textViewFrame = textView.frame;
textView.frame = CGRectMake(0.0, 0.0, textViewFrame.size.width, dataTextHeight);
UILabel *textLabel = [cell.contentView viewWithTag:textLabelTag];
CGRect textLabelFrame = textLabel.frame;
textLabel.frame = CGRectMake(10.0, 0.0, textLabelFrame.size.width, dataTextHeight);
textLabel.text = textData;
textLabel.backgroundColor= [UIColor clearColor];
textLabel.textAlignment = NSTextAlignmentCenter;
cell.backgroundColor = [UIColor colorWithWhite:0 alpha:.65];
cell.textLabel.numberOfLines = 0; // Multiline
cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.textLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
return cell;
}
Thanks in advance.
I saw a lot of solutions but all was wrong or uncomplet.
You can solve all problems with 5 lines in viewDidLoad and autolayout.
This for objetive C:
_tableView.delegate = self;
_tableView.dataSource = self;
self.tableView.estimatedRowHeight = 80;//the estimatedRowHeight but if is more this autoincremented with autolayout
self.tableView.rowHeight = UITableViewAutomaticDimension;
[self.tableView setNeedsLayout];
[self.tableView layoutIfNeeded];
self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0) ;
For swift 2.0:
self.tableView.estimatedRowHeight = 80
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.setNeedsLayout()
self.tableView.layoutIfNeeded()
self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0)
Now create your cell with xib or into tableview in your Storyboard
With this you no need implement nothing more or override. (Don forget number os lines 0) and the bottom label (constrain) downgrade "Content Hugging Priority -- Vertical to 250"
You can donwload the code in the next url:
https://github.com/jposes22/exampleTableCellCustomHeight
References: http://candycode.io/automatically-resizing-uitableviewcells-with-dynamic-text-height-using-auto-layout/
This is a part of my code which i used in my app. It works for me fine.Ping me if u need help.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
CGSize constraintSize = {230.0, 20000}; //230 is cell width & 20000 is max height for cell
CGSize neededSize = [ [NSString stringWithFormat:#"%#",[cellar objectAtIndex:indexPath.row]] sizeWithFont:[UIFont fontWithName:#"HelveticaNeue-Medium" size:15.0f] constrainedToSize:constraintSize lineBreakMode:UILineBreakModeCharacterWrap];
return MAX(45, neededSize.height +33);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
{ cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
CGSize constraintSize = {230.0, 20000};
UILabel* label = [[UILabel alloc] init];
[label setNumberOfLines:0];
label.backgroundColor = [UIColor clearColor];
[label setFont:[UIFont fontWithName:#"HelveticaNeue-Medium" size:15.0f]];
label.adjustsFontSizeToFitWidth = NO;
CGSize neededSize = [ [NSString stringWithFormat:#"%#",[cellar objectAtIndex:indexPath.row] ] sizeWithFont:[UIFont fontWithName:#"HelveticaNeue-Medium" size:15.0f] constrainedToSize:constraintSize lineBreakMode:UILineBreakModeCharacterWrap];
// NSLog(#"Height%f",neededSize.height);
//NSLog(#"width%f",neededSize.width);
[label setText:[NSString stringWithFormat:#"%#",[cellar objectAtIndex:indexPath.row] ]];
[label setFrame:CGRectMake(10, 2, 230, MAX(neededSize.height+30, 44.0f))];
[[cell contentView] addSubview:label];
cell.selectionStyle=UITableViewCellSelectionStyleNone;
return cell;
}
Hope it helps.!!!
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return "your content height";
}
I have a UITextView inside a UITableViewCell. It's working as expected except that I can't dismiss the autocorrection suggestions that pop up. This is what my -tableView:cellForRowAtIndexPath: method looks like:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *messageCellIdentifier = #"MessageCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:messageCellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:messageCellIdentifier];
}
// Set the background view of the cell to be transparent
UIView *backView = [[UIView alloc] initWithFrame:CGRectZero];
backView.backgroundColor = [UIColor clearColor];
cell.backgroundView = backView;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIImage *ballonImage = [[UIImage imageNamed:#"ChatBubbleGray.png"] stretchableImageWithLeftCapWidth:24 topCapHeight:15];
NSString *text = #"Touch To Type";
// This imageView will be the background of the UITextView
UIImageView *balloon = [[UIImageView alloc] initWithImage:ballonImage];
balloon.frame = CGRectMake(0.0, 0.0, 300, 140);
CGRect textViewFrame;
textViewFrame.origin.x = balloon.frame.origin.x + 10;
textViewFrame.origin.y = balloon.frame.origin.y + 5;
textViewFrame.size.width = balloon.frame.size.width - 12;
textViewFrame.size.height = balloon.frame.size.height - 15;
self.messageTextView = [[UITextView alloc] initWithFrame:textViewFrame];
self.messageTextView.backgroundColor = [UIColor clearColor];
self.messageTextView.returnKeyType = UIReturnKeyDefault;
self.messageTextView.editable = YES;
self.messageTextView.scrollEnabled = YES;
self.messageTextView.autocorrectionType = UITextAutocorrectionTypeYes;
self.messageTextView.autocapitalizationType = UITextAutocapitalizationTypeSentences;
self.messageTextView.delegate = self;
self.messageTextView.text = text;
self.messageTextView.font = [UIFont systemFontOfSize:14.0];
[balloon addSubview:self.messageTextView];
[cell.contentView addSubview:balloon];
return cell;
}
#Peter Warbo: I'm suspecting following:
By default UIImageView's userInteraction property is set to NO. Set it to YES on your ballon image view object.
balloon.userInteractionEnabled = YES;
HTH