Add Arrays of (parse.com) to a UICollectionView SubView - ios

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

Related

The tableview row cannot be load correctly

The UITableView row cannot be loaded after row 13. The data reload from 0 again.
i found out that the row is loaded until 13. And the row will start again from beginning.
If I set the height of each row to 20. All the row can be loaded in one screen then everything fine.
but I need to set the height to 40. then it has the problem.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = #"GroupsCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
NSLog(#"test indexpath = %ld",(long)indexPath.row);
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
}
if(indexPath.row == 0){
UIImageView *profileImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10.0, 10, 80.0, 80.0)];
NSString *url = [[NSString alloc] init];
NSString *tempurl =self.iconimgpath;
NSLog(#"tempurl = %#",tempurl);
url = [NSString stringWithFormat:#"%#",tempurl];
NSURL * imageURL = [NSURL URLWithString:url];
profileImageView.contentMode = UIViewContentModeScaleAspectFit;
[profileImageView sd_setImageWithURL:imageURL placeholderImage:[UIImage imageNamed:#"loadinglogo.png"]];
profileImageView.tag = 11;
if([cell.contentView viewWithTag:11])
[[cell.contentView viewWithTag:11] removeFromSuperview];
[cell.contentView addSubview:profileImageView];
//[cell.contentView addSubview:profileImageView];
}
else{
if(_feedItems.count>0 && (indexPath.row > 0))
{
UILabel * groupnamelabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 15.0, 300,20)];
groupnamelabel.text = [_feedItems[indexPath.row-1] groupname];
//groupnamelabel.font = [UIFont fontWithName:#"TrebuchetMS-Bold" size:18];
groupnamelabel.tag = 99;
if([cell.contentView viewWithTag:99]){
[[cell.contentView viewWithTag:99] removeFromSuperview];
}
[groupnamelabel setFont:[UIFont systemFontOfSize:15]];
[cell.contentView addSubview:groupnamelabel];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(pushAction:)];
[groupnamelabel addGestureRecognizer:tap];
groupnamelabel.userInteractionEnabled = YES;
}
}
return cell;
I found out the problem is
self.MyGrouptableview = [[UITableView alloc] initWithFrame:CGRectMake(0,65,screenWidth,screenHeight-150) style:UITableViewStylePlain];
If I set the height of the tableview long enough everything would be alright but the user cannot scroll to the bottom.

Reused cell keeps getting double labels

So, I'm trying to implement a UITableView with custom cells. However, when I scroll text is being overlaid on other text in reused cells.
This is how I construct the cell:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * reuseIdentifier = #"programmaticCell";
MGSwipeTableCell * cell = [self.tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
if (!cell) {
cell = [[MGSwipeTableCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
}
CGFloat brightness = [UIScreen mainScreen].brightness;
if (brightness < 0.4) {
cell.backgroundColor = [UIColor darkGrayColor];
cell.textLabel.textColor = [UIColor whiteColor];
cell.detailTextLabel.textColor = [UIColor whiteColor];
}
NSString *imageUrl = [NSString stringWithFormat: #"%#", [self.streams[indexPath.row] plaatje]];
UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 55, 55)];
__block UIActivityIndicatorView *activityIndicator;
__weak UIImageView *weakImageView = image;
[image sd_setImageWithURL: imageUrl
placeholderImage:[UIImage imageNamed:#"tile-blue.png"]
options:SDWebImageProgressiveDownload
progress:^(NSInteger receivedSize, NSInteger expectedSize) {
if (!activityIndicator) {
[weakImageView addSubview:activityIndicator = [UIActivityIndicatorView.alloc initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]];
activityIndicator.center = weakImageView.center;
[activityIndicator startAnimating];
}
}
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
[activityIndicator removeFromSuperview];
activityIndicator = nil;
}];
UIView *cellView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 65)];
[cellView addSubview:image ];
UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(65, 15, self.view.frame.size.width, 20)];
nameLabel.text = [[self.streams[indexPath.row] name] capitalizedString];
nameLabel.textAlignment = NSTextAlignmentLeft;
nameLabel.font = [UIFont systemFontOfSize:20];
UILabel *publishLabel = [[UILabel alloc] initWithFrame:CGRectMake(65, 35, 100, 20)];
publishLabel.text = [[self.streams[indexPath.row] published] capitalizedString];
publishLabel.textAlignment = NSTextAlignmentLeft;
publishLabel.font = [UIFont systemFontOfSize:13];
if (brightness < 0.4) {
nameLabel.textColor = [UIColor whiteColor];
publishLabel.textColor = [UIColor whiteColor];
} else {
nameLabel.textColor = [UIColor blackColor];
publishLabel.textColor = [UIColor blackColor];
}
[cellView addSubview:nameLabel];
[cellView addSubview:publishLabel];
[cell addSubview:cellView];
[cell sendSubviewToBack:cellView];
cell.delegate = self; //optional
return cell;
}
And this is MGSwipeTableCell's prepareForReuse method that I rewrote:
-(void) prepareForReuse
{
[super prepareForReuse];
self.textLabel.text = nil;
self.detailTextLabel.text = nil;
self.imageView.image = nil;
[self cleanViews];
BOOL cleanButtons = _delegate && [_delegate respondsToSelector:#selector(swipeTableCell:swipeButtonsForDirection:swipeSettings:expansionSettings:)];
[self initViews:cleanButtons];
}
What am I doing wrong here?
Every time your method is called, you try to dequeue a cell. This is correct.
However, all of your code after that assumes you're getting a new cell, which is incorrect. You're making new labels each time, and adding them to the cell each time, when the dequeued cells already have these labels.
Either use viewWithTag: to check if the labels are there (and only create them if they're not), or make a custom table cell subclass with properties for each label.
Your implementation of tableview:cellForRowAtIndexPath: needs to be idempotent, meaning you should write your code so that it can be called multiple times over and over, and always return an identical cell.
Your problem may be because you are recreating the items for the cells every time.
Try sub-classing UITableViewCell and move all of your code into it. Set up properties for all of your labels/imageViews/etc. You can even create an xib and use autolayout with IBOutlets to manage the way the cell looks.
If you end up creating an xib though, just be aware that you have to register the nib in your tableView class before you can use it.
self.tableView registerNib:[UINib nibWithNibName:#"nameOfXibFile" bundle:nil]; forCellReuseIdentifier:#"customIdentifier"];
When you do this, it will be referencing the same label/image/etc objects each time it reuses the cell and won't be creating new objects.

Where is there unwanted white space at the bottom of my last UITableView cell?

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

Tableview is not displaying any cells or rows content in new pushed viewController

I'm not sure what I'm missing but I'm trying to display a new viewController and passing some data to it, but the problem is when this new viewController gets pushed it doesn't display the cells or rows content like labels, textfields and so on..
This is how I'm pushing from one controller to another..
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
BillComparatorViewController *vc = [[BillComparatorViewController alloc] init];
vc.selectedInstitution = [self.myInstitution objectAtIndex:indexPath.row];
vc.managedObjectContext = self.managedObjectContext;
[self.view endEditing:YES];
[self.navigationController pushViewController:vc animated:YES];
}
Then in my new pushed view controller this is my cellForRowAtIndexPath function..
//UITableView Delegate + Datasource
- (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
}
for (UIView *view in cell.contentView.subviews)
[view removeFromSuperview];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.backgroundColor = [UIColor whiteColor];
cell.textLabel.text = [self.labels objectAtIndex:indexPath.row];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.text = [self.labels objectAtIndex:indexPath.row];
CGFloat i = [[self.rowHeights objectAtIndex:indexPath.row] floatValue];
UILabel *cellLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 10, 280, 15)];
cellLabel.font = [UIFont fontWithName:kFONTNAME size:kSystemFontSizeRows];
if ([[self.tableViewElements objectAtIndex:indexPath.row] isKindOfClass:[UIButton class]]){
cell.textLabel.font = [UIFont fontWithName:kFONTNAME size:kSystemFontSizeRows];
cell.backgroundColor = [UIColor lightGrayColor];
[cell.contentView addSubview:[self.tableViewElements objectAtIndex:indexPath.row]];
[cell.contentView addSubview:arrow];
}
else if (i > kTableRowHeight)
{
cell.textLabel.text = nil;
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, kElementWidth/2, 75)];
lbl.text = [self.labels objectAtIndex:indexPath.row];
lbl.font = _myFont;
lbl.numberOfLines = 0;
lbl.lineBreakMode = NSLineBreakByWordWrapping;
lbl.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview:[self.tableViewElements objectAtIndex:indexPath.row]];
[cell.contentView addSubview:lbl];
if ([[self.tableViewElements objectAtIndex:indexPath.row] isKindOfClass:[UISwitch class]])
{
[cell.contentView addSubview:[self.tableViewElements objectAtIndex:indexPath.row]];
}
if ([[self.tableViewElements objectAtIndex:indexPath.row] isKindOfClass:[UITextField class]])
{
// Can make a class for this cell's contentview, however it never repeats in code
UITextField* txtField = [self.tableViewElements objectAtIndex:indexPath.row];
txtField.textColor = kBlueColor;
txtField.textAlignment = NSTextAlignmentLeft;
txtField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; // iOS 6 support
NSString *imageName = #"image";
NSString *arrowName = #"image1";
if (selectedRow == indexPath.row)
{
imageName = #"image";
arrowName = #"image1";
txtField.textColor = [UIColor whiteColor];
}
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(2*kElementWidth/3 -12, 23, 135, 27)];
imgView.image = [UIImage imageNamed:imageName];
[cell.contentView addSubview:imgView];
UIImageView *arrowView = [[UIImageView alloc] initWithFrame:CGRectMake(kElementWidth+10, 31, 8.5, 10)];
arrowView.image = [UIImage imageNamed:arrowName];
[cell.contentView addSubview:arrowView];
[cell.contentView addSubview:txtField];
}
}
else
{
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.text = [self.labels objectAtIndex:indexPath.row];
cell.textLabel.font = _myFontSmall;
cell.textLabel.textColor = kBlueColor;
cell.textLabel.backgroundColor = [UIColor clearColor];
if ([[self.tableViewElements objectAtIndex:indexPath.row] isKindOfClass:[UITextField class]])
{
// Can make a class for this cell's contentview, however it never repeats in code
UITextField* txtField = [self.tableViewElements objectAtIndex:indexPath.row];
txtField.textColor = kBlueColor;
txtField.textAlignment = NSTextAlignmentLeft;
txtField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; // iOS 6 support
NSString *imageName = #"image";
NSString *arrowName = #"image1";
if (selectedRow == indexPath.row)
{
imageName = #"image";
arrowName = #"image2";
txtField.textColor = [UIColor whiteColor];
}
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(2*kElementWidth/3 -12, 12, 135, 27)];
imgView.image = [UIImage imageNamed:imageName];
[cell.contentView addSubview:imgView];
UIImageView *arrowView = [[UIImageView alloc] initWithFrame:CGRectMake(kElementWidth+10, 20, 8.5, 10)];
arrowView.image = [UIImage imageNamed:arrowName];
[cell.contentView addSubview:arrowView];
[cell.contentView addSubview:txtField];
}
if (isSearching)
{
cellLabel.text = [searchElements objectAtIndex:indexPath.row];
[cell.contentView addSubview:cellLabel];
}
}
return cell;
}
It's a bit long sorry but I think it was important to post it..
UPDATE
This is how the problem happens, when user select a row within the current viewcontroller didSelectRowAtIndexPath calls a new viewcontroller and pushes this controller but if the user does this while searching with the keyboard in the screen is when the problem happens that the new viewcontroller pushed doenst show any content in its tableview..
SOLVED
Within my cellForRowAtIndexPath
[cell setTranslatesAutoresizingMaskIntoConstraints:NO];
The issue is with Autolayout. I had the same problem with iOS 8 beta. (I know you're not using i OS 8 but still).
Try turning it off. Should sort the issue out.
i think the problem is initiating the object of BillComparatorViewController.
You do like this .You may get solution
BillComparatorViewController *vc = [[BillComparatorViewController alloc] initWithNibName:"BillComparatorViewController" Bundle:nil];

Tableview forgetting selectedSegment in UISegmentedControl?

If i select some segments and then scroll the tableView down, it forgets my selected segments?
What am I do'ing wrong? Or what am I missing? It looks like it resets the cell every time, but I've tried to remove the cell = nil; but with no luck. All the code I think might have impact on this is here:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"FancyCell"];
cell = nil;
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"FancyCell"];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
// add the segmentedControl when you create a new cell
UIImage *correctImageGreen = [[UIImage imageNamed:#"green.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
UIImage *correctImageGul = [[UIImage imageNamed:#"gul.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
UIImage *correctImageRed = [[UIImage imageNamed:#"red.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
NSArray *itemArray = [NSArray arrayWithObjects: correctImageGreen, correctImageGul, correctImageRed, nil];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
segmentedControl.frame = CGRectMake(308, 8, 150, 28);
[cell.contentView addSubview:segmentedControl];
// add an action so we can change our model if the view changes
[segmentedControl addTarget:self action:#selector(didChangeSegmentedControl:) forControlEvents:UIControlEventValueChanged];
// use a tag so we can retrieve the segmentedControl later
segmentedControl.tag = 42;
}
// either if the cell could be dequeued or you created a new cell,
// segmentedControl will contain a valid instance
UISegmentedControl *segmentedControl = (UISegmentedControl *)[cell.contentView viewWithTag:42];
UIImage *comment = [UIImage imageNamed:#"Checkmark-hvid"];
UIImage *imageRef = [UIImage imageNamed:#"Checkmark-hvid"];
UIImageView *commentView = [[UIImageView alloc] initWithImage: comment];
UIImageView *imageRefView = [[UIImageView alloc] initWithImage: imageRef];
commentView.frame = CGRectMake(625, 5, 30, 30);
imageRefView.frame = CGRectMake(515, 5, 30, 30);
commentView.tag = 98;
imageRefView.tag = 99;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
boolean_t didGetStates = [defaults boolForKey:#"didGetStates"];
if (didGetStates) {
NSDictionary *dic = [tableData objectAtIndex:indexPath.row];
int selectedState = [[dic valueForKey:#"State"] intValue];
[cell.contentView addSubview:segmentedControl];
if (selectedState == -1) {
segmentedControl.selectedSegmentIndex = -1;
}
else {
segmentedControl.selectedSegmentIndex = selectedState;
}
int comment = [[dic valueForKey:#"Comment"] intValue];
int imageRef = [[dic valueForKey:#"Foto"] intValue];
if (comment == 0) {
[cell.contentView addSubview:commentView];
}
else {
[[cell.contentView viewWithTag:98]removeFromSuperview];
}
if (imageRef == 0) {
[cell.contentView addSubview:imageRefView];
}
else {
[[cell.contentView viewWithTag:99]removeFromSuperview];
}
}
MBFancyObject *object = _objects[indexPath.row];
cell.textLabel.text = object.title;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
object.selectedIndex = segmentedControl.selectedSegmentIndex;
object.currentIndexRow = indexPath.row;
cell.backgroundColor = [UIColor clearColor];
cell.textLabel.textColor = [UIColor whiteColor];
return cell;
}
The action that is called, when a segment is chosen..
- (IBAction)didChangeSegmentedControl:(UISegmentedControl *)sender {
// transform the origin of the cell to the frame of the tableView
CGPoint senderOriginInTableView = [self.tableView convertPoint:CGPointZero fromView:sender];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:senderOriginInTableView];
NSAssert(indexPath, #"must have a valid indexPath");
MBFancyObject *object = _objects[indexPath.row];
object.selectedIndex = sender.selectedSegmentIndex;
}
If you got any idea please write an answer or if you need more information tell me!! :)
THANK YOU!!!
Mikkel - The 15 year old iDeveloper! ;)
You are misunderstanding how table view cells work. They are not for saving state information, they are for presenting it, and interacting with the user.
When a table view cell is scrolled off-screen, the system tosses it into a recycle queue, and any field settings in the cell are lost.
When a user interacts with the controls in your table view, you should immediately save the changed information to your model (data storage). Then, when the table view asks you for a cell in the tableView:cellForRowAtIndexPath: method, you should create and FULLY configure a cell with the values from your model.
I found out that i forgot that i get data from my database, witch returns -1. And if I choose segment 2 and then scroll down and then back up, it show the value from the database :) This was fixable by adding a boolan to check where it should look fore the selected segment :) Now it looks like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"FancyCell"];
cell = nil;
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"FancyCell"];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
// add the segmentedControl when you create a new cell
UIImage *correctImageGreen = [[UIImage imageNamed:#"green.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
UIImage *correctImageGul = [[UIImage imageNamed:#"gul.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
UIImage *correctImageRed = [[UIImage imageNamed:#"red.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
NSArray *itemArray = [NSArray arrayWithObjects: correctImageGreen, correctImageGul, correctImageRed, nil];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
segmentedControl.frame = CGRectMake(308, 8, 150, 28);
[cell.contentView addSubview:segmentedControl];
// add an action so we can change our model if the view changes
[segmentedControl addTarget:self action:#selector(didChangeSegmentedControl:) forControlEvents:UIControlEventValueChanged];
// use a tag so we can retrieve the segmentedControl later
segmentedControl.tag = 42;
}
// either if the cell could be dequeued or you created a new cell,
// segmentedControl will contain a valid instance
UISegmentedControl *segmentedControl = (UISegmentedControl *)[cell.contentView viewWithTag:42];
UIImage *comment = [UIImage imageNamed:#"Checkmark-hvid"];
UIImage *imageRef = [UIImage imageNamed:#"Checkmark-hvid"];
UIImageView *commentView = [[UIImageView alloc] initWithImage: comment];
UIImageView *imageRefView = [[UIImageView alloc] initWithImage: imageRef];
commentView.frame = CGRectMake(625, 5, 30, 30);
imageRefView.frame = CGRectMake(515, 5, 30, 30);
commentView.tag = 98;
imageRefView.tag = 99;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
boolean_t didGetStates = [defaults boolForKey:#"didGetStates"];
boolean_t didSelectState = [defaults boolForKey:#"didSelectState"];
MBFancyObject *object = _objects[indexPath.row];
if (didGetStates) {
NSDictionary *dic = [tableData objectAtIndex:indexPath.row];
if (didSelectState) {
segmentedControl.selectedSegmentIndex = object.selectedIndex;
}
else {
int selectedState = [[dic valueForKey:#"State"] intValue];
[cell.contentView addSubview:segmentedControl];
if (selectedState == -1) {
segmentedControl.selectedSegmentIndex = -1;
}
else {
segmentedControl.selectedSegmentIndex = selectedState;
}
}
int comment = [[dic valueForKey:#"Comment"] intValue];
int imageRef = [[dic valueForKey:#"Foto"] intValue];
if (comment == 0) {
[cell.contentView addSubview:commentView];
}
else {
[[cell.contentView viewWithTag:98]removeFromSuperview];
}
if (imageRef == 0) {
[cell.contentView addSubview:imageRefView];
}
else {
[[cell.contentView viewWithTag:99]removeFromSuperview];
}
}
cell.textLabel.text = object.title;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
object.selectedIndex = segmentedControl.selectedSegmentIndex;
object.currentIndexRow = indexPath.row;
cell.backgroundColor = [UIColor clearColor];
cell.textLabel.textColor = [UIColor whiteColor];
return cell;
}
And the segmentedControl's action:
- (IBAction)didChangeSegmentedControl:(UISegmentedControl *)sender {
// transform the origin of the cell to the frame of the tableView
CGPoint senderOriginInTableView = [self.tableView convertPoint:CGPointZero fromView:sender];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:senderOriginInTableView];
NSAssert(indexPath, #"must have a valid indexPath");
MBFancyObject *object = _objects[indexPath.row];
object.selectedIndex = sender.selectedSegmentIndex;
[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:#"didSelectState"];
}

Resources