Segmentcontrol in tableviewcell - ios

I got this tableview with segmented controls in each cell. I get some data from my database that i put into the cells segmented control. But how to set no segment chosen? If noting is found in the database it returns -1. I tried the: segmentedControl.selectedSegmentIndex = -1;, but with no luck. It looks like it set the segmentedControl.selectedSegmentIndex = 0;, be course segment with index 0 is selected no matter what (even if i get a result or not). See screenshots to understand :)
Btw I can select as many segments as I want in each segmented control..
Why is this possible? Will the other problem fix this? :)
THANK YOU!
My code for creating the cells is:
UITableViewCell *cell = nil;
cell = [tableView dequeueReusableCellWithIdentifier:#"StateCell"];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseI dentifier:#"StateCell"];
}
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, 7, 150, 28);
[segmentedControl addTarget:self action:#selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
int newIndexPath = indexPath.row + 1;
NSString *indexPathKey = [NSString stringWithFormat:#"%i", newIndexPath];
NSString *selectedState = [statefieldData valueForKey:[NSString stringWithFormat:#"StateField%#", indexPathKey]];
int selectedIndexInt = [selectedState intValue];
if (selectedIndexInt == -1) {
segmentedControl.selectedSegmentIndex = -1;
}
else {
segmentedControl.selectedSegmentIndex = selectedIndexInt;
}
[cell.contentView addSubview:segmentedControl];
cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
cell.textLabel.textColor = [UIColor whiteColor];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
[self.tableView setBackgroundColor:[UIColor colorWithRed:37 green:37 blue:37 alpha:0]];
cell.backgroundColor = [UIColor clearColor];
return cell;
[[self tableView] reloadData];

The documentation states:
selectedSegmentIndex
The default value is UISegmentedControlNoSegment (no segment selected) until the user touches a segment. Set this property to -1 to turn off the current selection.
If you are setting -1 (UISegmentedControlNoSegment), and it is not deselecting the segment, then there is something else you are doing wrong that we cannot see.

Related

Partially custom UITableViewCell acting funny if there are more than 8 rows

I have a UIViewController that uses a UITableView to display an array. This array gets its data from fetching from Core Data. All works well except having more then 8 entries displayed at once results in rows appearing over other rows when the table view is scrolled. Periodically the text in the rows begins to become slightly fuzzy too. Very weird.
Here is the code of my 'rowForCell" method.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//Creates a new cell for every row (as in, every time this method is called).
//UITableViewCell *aCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
//'alloc init' is NOT called here therefore a cell object has to be made inside the table view in the storyboard (which I've done and named cell). This is a more effecient and better way then 'alloc init'. Cells are dequeued & reused.
UITableViewCell *aCell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if (aCell == nil)
{
aCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:#"cell"];
}
//Makes sure the separator doesn't have that little gap in the beginning.
//NOTE: This MUST be here and "_tableView.separatorInset = UIEdgeInsetsZero;" must exist inside [self extraTableViewParameter]!
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
aCell.layoutMargins = UIEdgeInsetsZero;
aCell.preservesSuperviewLayoutMargins = NO;
}
//Cell details.
aCell.backgroundColor = [UIColor clearColor];
aCell.textLabel.textColor = [UIColor whiteColor];
//aCell.textLabel.font = [UIFont fontWithName:#"SanFrancisco" size:20];
aCell.detailTextLabel.textColor = [UIColor lightGrayColor];
//aCell.detailTextLabel.font = [UIFont fontWithName:#"SanFrancisco" size:20];
//Fill cell with data.
//NSDictionary *item = [_tableData objectAtIndex:indexPath.row]; //[_fetchArray objectAtIndex:indexPath.row];
//AssetsPartners *items = [_fetchArray objectAtIndex:indexPath.row]; //Using this line of code, instead of the bottom one, will result in _fetchArray NOT being sorted.
AssetsPartners *items = [_fetchedResultsController objectAtIndexPath:indexPath]; //Ask '_fetchedResultsController' what's at this particular indexPath right now. Also alphabetically sorts the array list.
//CUSTOM LABEL instead of standard '.textLabel.text' because 'items.name' is sometimes too long & covers up price: looks messy.
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(65.0, 15.0, 150.0, 30.0)];
label.textColor = [UIColor whiteColor];
label.text = items.name;
[aCell.contentView addSubview:label];
aCell.textLabel.text = #""; //Make sure this is empty!
//aCell.textLabel.text = items.name; //item[#"title"]; //Preiously, was just this with out the UILabel.
NSInteger anInteger = [items.balance integerValue];
aCell.detailTextLabel.text = [NSString stringWithFormat:#"%# P", [self addWhitespacesTo:anInteger]]; //item[#"balance"]];
//Check if it's appropriate to add image to cell or not.
if (items.photo == nil)
{
NSLog(#"No image.");
}
else
{
NSString *iconName = [self cutOutString:#"bizzer://" fromString:items.photo]; //Get rid of "bizzer://" from string value.
//Standard UITableViewCell accessors/parameters. Only used to create a clear image to shift text over.
aCell.imageView.image = [UIImage imageNamed:iconName]; //Inputs appropriate icon into cell image.
[self turnIcon:aCell.imageView toColor:#"clearColor"]; //Changes icons color accordingly.
//Entirely new UIImageView for every UITableViewCell (to tweak the frame size & position).
UIImageView *newImgView = [[UIImageView alloc] initWithFrame:CGRectMake(10.0, 15.0, 35.0, 35.0)];
newImgView.image = [UIImage imageNamed:iconName];
[aCell.contentView addSubview:newImgView];
[self turnIcon:newImgView toColor:items.color];
}
return aCell;
}
Try rearranging your code as follow
if (aCell == nil)
{
aCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:#"cell"];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(65.0, 15.0, 150.0, 30.0)];
label.textColor = [UIColor whiteColor];
label.tag = 999;
[aCell.contentView addSubview:label];
}
UILabel *label = (UILabel *)[aCell.contentView viewWithTag:999];
AssetsPartners *items = [_fetchedResultsController objectAtIndexPath:indexPath];
label.text = items.name;
You are adding a label without considering that the cell may have been reused. You should move that code into your if (aCell == nil) block so that you only do it once per cell. Same for the image view.

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

UITableViewCell separator line disappears on scroll

I'm trying to have a separator cell with a custom image. I did try something like that:
In my cellForRowAtIndexPath:
NSString *cellIdentifier = [NSString stringWithFormat:#"identifier"];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:19];
cell.textLabel.text = [self.menuItems objectAtIndex:indexPath.row];
cell.textLabel.textColor = [UIColor colorWithRed:128/255.0f green:129/255.0f blue:132/255.0f alpha:1.0f];
cell.backgroundColor = [UIColor whiteColor];
UIImageView *imagView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"reaL.png"]];
imagView.frame = CGRectMake(0, cellHeight, cellWidth, 1);
[cell.contentView addSubview:imagView];
switch (indexPath.row) {
case 0:
cell.imageView.image = [self imageWithImage:[UIImage imageNamed:#"img1.png"] scaledToSize:CGSizeMake(27, 27)];
cell.imageView.highlightedImage = [self imageWithImage:[UIImage imageNamed:#"route.png"] scaledToSize:CGSizeMake(27, 27)];
break;
case 1:
cell.imageView.image = [self imageWithImage:[UIImage imageNamed:#"img.png"] scaledToSize:CGSizeMake(27, 27)];
cell.imageView.highlightedImage = [self imageWithImage:[UIImage imageNamed:#"money.png"] scaledToSize:CGSizeMake(27, 27)];
break;
case 2:
cell.imageView.image = [self imageWithImage:[UIImage imageNamed:#"auto.png"] scaledToSize:CGSizeMake(27, 27)];
cell.imageView.highlightedImage = [self imageWithImage:[UIImage imageNamed:#"cars.png"] scaledToSize:CGSizeMake(27, 27)];
break;
case 3:
cell.imageView.image = [self imageWithImage:[UIImage imageNamed:#"impostazioni.png"] scaledToSize:CGSizeMake(27, 27)];
cell.imageView.highlightedImage = [self imageWithImage:[UIImage imageNamed:#"impostazioni.png"] scaledToSize:CGSizeMake(27, 27)];
// cell.imageView.contentMode = UIViewContentModeScaleAspectFill;
break;
case 4:
cell.imageView.image = [self imageWithImage:[UIImage imageNamed:#"info.png"] scaledToSize:CGSizeMake(27, 27)];
cell.imageView.highlightedImage = [self imageWithImage:[UIImage imageNamed:#"info.png"] scaledToSize:CGSizeMake(27, 27)];
break;
default:
break;
}
return cell;
When I lunch the app everything is good, but when I scroll the the table, or when I select a cell the separator lines disappear. How I can have a permanent custom line separator?
You're not creating cells properly in the first place. Here's a few tips to try that might help with the issue you're running into.
First off, since ios6, Apple now allows us to pre-register the classes we're using to dequeue cells so there is no more deed to do the !cell check. In your view did load, you'll want to do something akin to:
[self.tableView registerClass:[CustomTableViewCellClass class] forCellReuseIdentifier:customIdentifier];
This will allow you to dequeue the cell properly every time, as in:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:customIdentifier];
Next, and this is where I think you're running into issues. You're creating an image view and adding it to the cell every time the cell is dequeued.
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"reaL.png"]];
imageView.frame = CGRectMake(0, cellHeight, cellWidth, 1);
[cell.contentView addSubview:imageView];
You only need to do this the first time the cell is created otherwise you're going to be adding constantly UIImageViews to the top of the cell every time a cell is re-used. A better pattern for this situations would be to have a UIImageView* reference on the custom cell itself. When the cell is dequeue, set the image and frame then. This way the UIImageView is only created once and added to the cell once.
Best of luck!

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

Different images in different cells of tableViewController are not working properly

I have made a tableViewController. I want to give different images to the 1st and 7th index cell. This is a code snippet inside my cellForRowAtIndexPath delegate method. It initializes the cells properly in the beginning but when I scroll up and down several times then it also starts to give the "button4.png" in the accessory view of other cells.
UIImage *indicatorImage;
if(indexPath.row==0||indexPath.row==6)
{
indicatorImage = [UIImage imageNamed:#"button4.png"];
}
else
{
indicatorImage = [UIImage imageNamed:#"img-arrow.png"];
}
cell.accessoryView =
[[UIImageView alloc]
initWithImage:indicatorImage];
What can be the possible reason for this?
The complete code of the function is a little messy, but I am posting it here:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
selection=self.tabBarController.selectedIndex;
static NSString *CellIdentifier = #"Cell";
UILabel *topLabel;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
UIImage *indicatorImage;
if(indexPath.row==0||indexPath.row==6)
{
indicatorImage = [UIImage imageNamed:#"button4.png"];
}
else
{
indicatorImage = [UIImage imageNamed:#"img-arrow.png"];
}
cell.accessoryView =
[[UIImageView alloc]
initWithImage:indicatorImage];
cell.accessoryView =
[[UIImageView alloc]
initWithImage:indicatorImage];
const CGFloat LABEL_HEIGHT = 20;
topLabel =
[[UILabel alloc]
initWithFrame:
CGRectMake(
2.0 * cell.indentationWidth,
0.5 * (tableView.rowHeight - 2 * LABEL_HEIGHT),
tableView.bounds.size.width -
4.0 * cell.indentationWidth
- indicatorImage.size.width,
LABEL_HEIGHT)];
[cell.contentView addSubview:topLabel];
topLabel.backgroundColor = [UIColor clearColor];
topLabel.shadowColor = [UIColor whiteColor];
topLabel.shadowOffset = CGSizeMake(0, 1);
topLabel.textColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0];
topLabel.highlightedTextColor = [UIColor colorWithRed:1.0 green:1.0 blue:0.9 alpha:1.0];
topLabel.font = [UIFont systemFontOfSize:[UIFont labelFontSize]];
topLabel.tag=10;
cell.backgroundView =
[[UIImageView alloc] init];
cell.selectedBackgroundView =
[[UIImageView alloc] init];
}
}
else
{
topLabel = (UILabel *)[cell viewWithTag:10];
}
UIImage *rowBackground;
UIImage *selectionBackground;
rowBackground = [UIImage imageNamed:#"topAndBottomRow.png"];
selectionBackground = [UIImage imageNamed:#"topAndBottomRowSelected.png"];
if(indexPath.row==0||indexPath.row==6)
{
rowBackground = [UIImage imageNamed:#"topAndBottomRowSelected.png"];
selectionBackground = [UIImage imageNamed:#"topAndBottomRowSelected.png"];
topLabel.textColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0];
topLabel.highlightedTextColor = [UIColor colorWithRed:1.0 green:1.0 blue:0.9 alpha:1.0];
topLabel.font = [UIFont systemFontOfSize:20];
}
((UIImageView *)cell.backgroundView).image = rowBackground;
((UIImageView *)cell.selectedBackgroundView).image = selectionBackground;
NSString *object = _objects[indexPath.row];
NSString *str=[object description];
topLabel.text=[NSString stringWithFormat:#" %#",str];
return cell;
}
You are setting this image in your if (cell == nil) ... block in which you create and configure the cell. But you need to move this image setting outside of that if block because if the cell is being reused (ie you don't have to alloc and init), the old image will be reused. You should review anything inside that if statement for things that should change cell-by-cell, and move that outside of the if block.
When scrolling messes you up like this, it suggests that you're not completely initializing the contents of a REUSED UITableViewCell. While your code snippet says you do set it to something -- your result suggests that you aren't. You can look for that.
For instance, try setting the accessoryView to nil immediately after getting the cell and see if the problem goes away.

Resources