I'm thinking that this is an issue with reusing cells but I can't figure this out and would appreciate some additional eyes on it. I have a uitableviewcell subclass that compares two values, if one value is higher it changes the cell background to red, else it changes it to white. As I scroll, some cells are white that should be red and vice versa.
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
tut_MaintListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"maintCell" forIndexPath:indexPath];
// Configure the cell...
MaintItem *mItem = [self.fetchedResultsController objectAtIndexPath:indexPath];
[cell configureCellForEntry:mItem sendCar:self.carDetail];
return cell;
}
UITableViewCell Subclass
- (void)configureCellForEntry:(MaintItem *)mItem sendCar:(Car *)carDetails
{
self.itemLabel.text = [mItem valueForKey:#"item"];
self.actionLabel.text = [mItem valueForKey:#"action"];
self.engineLabel.text = [mItem valueForKey:#"engineCode"];
self.maintIDLabel.text = [[mItem valueForKey:#"maintID" ]stringValue];
// Grab the mileages recorded in the log for this maint item and turn it into a sorted array
NSArray *result = [[mItem.toLog valueForKey:#"mileage"] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"" ascending:YES]]];
// Determine mileage of next service
NSString *nextServiceMileage = [NSString stringWithFormat:#"%d", [mItem.intMileage intValue] + [[result lastObject] intValue]];
nextServiceMileageNS = #([nextServiceMileage intValue]);
if ([mItem.frequencyID isEqualToNumber:[NSNumber numberWithInt:3]])
{
NSString *timing = [[NSString alloc] initWithFormat:#" %# Once at %# miles or %# months", [mItem valueForKeyPath:#"frequencyID"], [mItem valueForKeyPath:#"intMileage"], [mItem valueForKeyPath:#"intMonth"]];
NSString *howOften = [[NSString alloc] initWithFormat:#" %#", timing];
self.howOftenLabel.text = howOften;
if (carDetails.mileage > nextServiceMileageNS)
{
self.backgroundColor = [UIColor redColor];
}
else
{
self.backgroundColor = [UIColor whiteColor];
}
}
else if ([mItem.frequencyID isEqualToNumber:[NSNumber numberWithInt:4]])
{
NSString *timing = [[NSString alloc] initWithFormat:#" %# Every %# miles or %# months, due at %# ", [mItem valueForKeyPath:#"frequencyID"], [mItem valueForKeyPath:#"intMileage"], [mItem valueForKeyPath:#"intMonth"], nextServiceMileage];
NSString *howOften = [[NSString alloc] initWithFormat:#" %#", timing];
self.howOftenLabel.text = howOften;
if (carDetails.mileage > nextServiceMileageNS)
{
self.backgroundColor = [UIColor redColor];
}
else
{
self.backgroundColor = [UIColor whiteColor];
}
}
else
{
NSString *howOften = [[NSString alloc] initWithFormat:#" %#", [mItem valueForKeyPath:#"frequencyID"]];
self.howOftenLabel.text = howOften;
}
}
The Solution is: you have to set the backgroundColor in the else part too. Better solution would be,
UIView *backgroundView;
if (condition_1) {
backgroundView = [UIView new];
[backgroundView setBackgroundColor:[UIColor whiteColor]];
} else if (condition_2) {
backgroundView = [UIView new];
[backgroundView setBackgroundColor:[UIColor redColor]];
} else {
// here you can set or leave it.
}
[self setBackgroundView:backgroundView];
hope it will work for you...
The solution was that I was comparing two NSnumber objects in the if statement. I changed
if (carDetails.mileage > nextServiceMileageNS)to if ([carDetails.mileage intvalue] > [nextServiceMileageNS intvalue]) and now it worked correctly. The way the random background were applied it seemed to be a cell reuse issue.
Related
I have two tables, one table for usernames, and one table for scores. I populate those tables with two arrays. The tables need to be in descending order based on the scores. I sort the array with the scores in it, but I am not sure how I can arrange the usernames to stick with their score, they are in a separate array, and a separate table from the scores table. Here is my code:
dictionary = [NSDictionary dictionaryWithObjects:matchesForUser forKeys:tableData];
sortedFirstArray = [dictionary allKeys];
sortedSecondArray = [dictionary objectsForKeys:sortedFirstArray notFoundMarker:[NSNull null]];
sortedSecondArray = [sortedSecondArray sortedArrayUsingSelector: #selector(compare:)];
I need the sortedFirstArray values to stick with their respective sortedSecondArray values in terms of their order in each of their arrays.
UPDATE
My code attempting to do the sorting:
PFQuery *query = [PFQuery queryWithClassName:#"_User"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (!error) {
entries = [NSMutableArray new];
for (PFObject *object in objects) {
NSLog(#"%#", object.objectId);
[tableData addObject:[object valueForKey:#"username"]];
[matchesForUser addObject:[object valueForKey:#"matches"]];
NSMutableDictionary* entry = [NSMutableDictionary new];
entry[#"username"] = [object valueForKey:#"username"];
entry[#"matches"] = [object valueForKey:#"matches"];
[entries addObject:entry];
//transfer = entries;
}
transfer = [entries sortedArrayUsingComparator:^NSComparisonResult(NSDictionary* a, NSDictionary* b) {
NSDate *first = [a objectForKey:#"matches"];
NSDate *second = [b objectForKey:#"matches"];
NSLog(first);
NSLog(second);
return [first compare:second];
}];
//dictionary = [NSDictionary dictionaryWithObjects:matchesForUser forKeys:tableData];
//sortedFirstArray = [dictionary allKeys];
//sortedSecondArray = [dictionary objectsForKeys:sortedFirstArray notFoundMarker:[NSNull null]];
//sortedSecondArray = [sortedSecondArray sortedArrayUsingSelector: #selector(compare:)];
[_tableView reloadData];
[_tableViewScore reloadData];
}else{
NSLog([error description]);
}
NSLog(#"***tabledata***");
NSLog([NSString stringWithFormat:#"%lu", (unsigned long)[tableData count]]);
NSLog(#"***matchesdata***");
NSLog([NSString stringWithFormat:#"%lu", (unsigned long)[matchesForUser count]]);
});
}];
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if(tableView.tag == 1) {
static NSString *simpleTableIdentifier = #"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
cell.textLabel.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size:16.0];
cell.textLabel.textColor = [UIColor colorWithRed:218.0f/255.0f green:247.0f/255.0f blue:220.0f/255.0f alpha:1.0f];
cell.backgroundColor = [UIColor colorWithRed:153.0f/255.0f green:211.0f/255.0f blue:212.0f/255.0f alpha:1.0f];
cell.layoutMargins = UIEdgeInsetsZero;
cell.preservesSuperviewLayoutMargins = NO;
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
UILabel *contentV = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 230, 44)];
contentV.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size:16.0];
contentV.textColor = [UIColor colorWithRed:218.0f/255.0f green:247.0f/255.0f blue:220.0f/255.0f alpha:1.0f];
contentV.backgroundColor = [UIColor colorWithRed:153.0f/255.0f green:211.0f/255.0f blue:212.0f/255.0f alpha:1.0f];
cell.contentView.layoutMargins = UIEdgeInsetsZero;
NSString *username2 = [[transfer objectAtIndex:indexPath.row] valueForKey:#"username"];
NSLog(#"***username***");
NSLog(username2);
contentV.text = username2;
[cell.contentView addSubview:contentV];
return cell;
}
else {
static NSString *simpleTableIdentifier = #"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
cell.textLabel.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size:16.0];
cell.textLabel.textColor = [UIColor colorWithRed:153.0f/255.0f green:211.0f/255.0f blue:212.0f/255.0f alpha:1.0f];
cell.backgroundColor = [UIColor colorWithRed:218.0f/255.0f green:247.0f/255.0f blue:220.0f/255.0f alpha:1.0f];
cell.textLabel.textAlignment = NSTextAlignmentCenter;
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
NSString *matchAmount = [[transfer objectAtIndex:indexPath.row] valueForKey:#"matches"];
NSLog(#"***matchamount***");
NSLog(matchAmount);
cell.textLabel.text = matchAmount;
return cell;
}
}
Instead of having two separate arrays and going trough the trouble of sorting one of them directly and try to figure out which entries of the other correspond to which in the sorted one, you should instead keep the paired entries of both arrays together in one entity (dictionary or instance of a custom class), and group those in your (single) array:
The actual property names etc. will vary for your code, but the general idea is like this:
self.entries = [NSMutableArray new];
for (int i=0; i < userNameArray.count; i++){
NSMutableDictionary* entry = [NSMutableDictionary new];
entry["userName"] = [userNameArray objectAtIndex: i];
entry["score" ] = [scoreArray objectAtIndex: i];
// ^ TODO: Make sure scoreArray has at least as many elements
// as userNameArray!
[self.entries addObject: entry];
}
self.entries = [self.entries sortedArrayUsingComparator:^NSComparisonResult(NSDictionary* a, NSDictionary* b) {
NSDate *first = [a objectForKey:"score"];
NSDate *second = [b objectForKey:"score"];
return [first compare:second];
}];
// (...)
UITableViewCell* tableView:(UITableView*) tableView cellForRowAtIndexPath:(NSIndexPath}) indexPath
{
NSDictionary* entry = [self.entries objectAtIndex: indexPath.row];
if (tableView == self.userNameTableView) {
// (dequeue user cell...)
cell.titleLabel.text = [entry objectForKey: "userName"];
return cell
}
else{
// (dequeue score cell...)
cell.titleLabel.text = [entry objectForKey: "score"];
return cell
}
}
Credit goes to NicolasMiari for helping me figure most of this out. Something weird was happening with the way the comparison was being made - and it was producing an unsorted result. This is how I sorted:
NSSortDescriptor * descriptor = [[NSSortDescriptor alloc] initWithKey:#"matches" ascending:NO selector:#selector(localizedStandardCompare:)];
NSArray *entrieshold = [entries sortedArrayUsingDescriptors:#[descriptor]];
transfer = [entrieshold copy];
It seemed like the most important thing for me was selector:#selector(localizedStandardCompare:). My use of copy also may be important...but I don't think so.
NSArray *sectionArray;
int sectionCount=0;
NSDictionary *orderedData;
NSString *checkInStr, *checkOutStr;
NSString *govtTaxes, *enhancementTotal, *grandTotal;
- (void)viewDidLoad {
[super viewDidLoad];
[self setupTable];
[self.bookingsTableView reloadData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void)viewDidDisappear:(BOOL)animated {
if(doesSendNotification){
NSLog(#"summary view disappeared");
[[NSNotificationCenter defaultCenter] postNotificationName:#"SummaryViewDismissedNotification" object:self];
}
}
-(void)viewWillAppear:(BOOL)animated {
[self.bookingsTableView reloadData];
}
-(void)setupTable {
self.bookingsTableView.rowHeight = UITableViewAutomaticDimension;
self.bookingsTableView.estimatedRowHeight = 50.0;
sectionArray = [[SummaryModel sharedInstance] getTableSections:self.s_sendEnhancementServerDict];
orderedData = [[SummaryModel sharedInstance] getOrderedData:self.s_sendEnhancementServerDict];
[self.bookingsTableView reloadData];
}
#pragma mark- UITableview delegate and datasource methods
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if(section==0){
return 3;
} else if (section>0 && section<(sectionCount-1)){
int rows=(int)[[orderedData objectForKey:(NSString*)[sectionArray objectAtIndex:section]] count];
return rows;
} else {
return 4;
}
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return (NSString*)[sectionArray objectAtIndex:section];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellIdentifier;
UITableViewCell *cell;
// UITableView *table = (UITableView*)[self.view viewWithTag:11];
if (indexPath.section==0 && indexPath.row>=0 && indexPath.row<=2) {
cellIdentifier =#"SplitCell";
cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
UILabel *l1 = (UILabel*)[cell viewWithTag:1];
UILabel *l2 = (UILabel*)[cell viewWithTag:2];
if(indexPath.row==0){
l1.attributedText = [self getStyledString1:#"Hotel Name"];
l2.attributedText = [self getStyledString:self.s_propertyName];
} else if(indexPath.row==1){
l1.attributedText = [self getStyledString1:#"Arrival Date:"];
l2.attributedText = [self getStyledString:checkInStr];
} else if(indexPath.row==2){
l1.attributedText = [self getStyledString1:#"Departure Date:"];
l2.attributedText = [self getStyledString:checkOutStr];
}
} else if (indexPath.section>0 && indexPath.section<(sectionCount-1)) {
// for(int i=0;i<5;i++){
cellIdentifier=#"VerticalLabelCell";
cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
UILabel *l3 = (UILabel*)[cell viewWithTag:3];
UILabel *l4 = (UILabel*)[cell viewWithTag:4];
l3.layer.backgroundColor = GOLDEN_COLOR.CGColor;
NSArray *roomTypeArray = [orderedData objectForKey:(NSString*)[sectionArray objectAtIndex:indexPath.section]];
NSDictionary *roomD = [roomTypeArray objectAtIndex:indexPath.row];
NSString *header = [roomD objectForKey:#"room_type_name"];
NSAttributedString *sH = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:#" %#",header] attributes:#{NSFontAttributeName:ARIAL_FONT_BOLD}];
l3.attributedText = sH;
int roomCount = [(NSNumber*)[roomD objectForKey:#"room_units"] intValue];
NSMutableAttributedString *labelText = [[NSMutableAttributedString alloc] init];
for(int i=0;i<roomCount;i++){
NSString *roomNo = [NSString stringWithFormat:#"\n Room # %d\n",i+1];
NSAttributedString *s = [[NSAttributedString alloc] initWithString:roomNo attributes:#{NSFontAttributeName:ARIAL_FONT_BOLD, NSUnderlineStyleAttributeName:#(NSUnderlineStyleSingle)}];
[labelText appendAttributedString:s];
NSString *adults = [NSString stringWithFormat:#" Adults: %# \t\t Max. Adults: %# \n",[roomD objectForKey:#"max_adults"],[roomD objectForKey:#"max_adults"]];
NSAttributedString *s1 = [[NSAttributedString alloc] initWithString:adults attributes:#{NSFontAttributeName:ARIAL_FONT_BOLD}];
[labelText appendAttributedString:s1];
NSArray *enhanc = [(NSArray*)[roomD objectForKey:#"room_features"] objectAtIndex:i];
for(int i=0;i<[enhanc count];i++){
[labelText appendAttributedString:[self getStyledString2:[NSString stringWithFormat:#" %#\n", [enhanc objectAtIndex:i]]]];
}
l4.attributedText = labelText;
}
} else if(indexPath.section==(sectionCount-1)){
cellIdentifier =#"SplitCell";
cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
UILabel *l1 = (UILabel*)[cell viewWithTag:1];
UILabel *l2 = (UILabel*)[cell viewWithTag:2];
if(indexPath.row==0){
l1.attributedText = [self getStyledString1:#"Room Charges:"];
l2.attributedText = [self getStyledString:[NSString stringWithFormat:#"£ %#", self.s_priceOfRooms]];
}else if(indexPath.row==1){
l1.attributedText = [self getStyledString1:#"Government Taxes:"];
l2.attributedText = [self getStyledString:[NSString stringWithFormat:#"£ %#", govtTaxes]];
}else if(indexPath.row==2){
l1.attributedText = [self getStyledString1:#"Enhancement Total:"];
l2.attributedText = [self getStyledString:[NSString stringWithFormat:#"£ %#", enhancementTotal]];
}else if(indexPath.row==3){
l1.attributedText = [self getStyledString1:#"Total Charges"];
l2.attributedText = [self getStyledString:[NSString stringWithFormat:#"£ %#", grandTotal]];
}
}
return cell;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
sectionCount = (int)[sectionArray count];
return sectionCount;
}
-(void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
view.tintColor = GOLDEN_COLOR;
}
-(NSAttributedString*)getStyledString:(NSString*)input {
NSAttributedString *str = [[NSAttributedString alloc] initWithString:input attributes:#{NSForegroundColorAttributeName:GOLDEN_COLOR, NSFontAttributeName:ARIAL_FONT}];
return str;
}
-(NSAttributedString*)getStyledString1:(NSString*)input {
NSAttributedString *str = [[NSAttributedString alloc] initWithString:input attributes:#{NSFontAttributeName:ARIAL_FONT_BOLD}];
return str;
}
-(NSAttributedString*)getStyledString2:(NSString*)input {
NSAttributedString *str = [[NSAttributedString alloc] initWithString:input attributes:#{NSFontAttributeName:ARIAL_FONT}];
return str;
}
I have made a ViewController and added a table view in it. Some data is populated in cells and then displayed.
When I run it, initially I don't see any data in my cells. But when the tableview is scrolled cells start showing the actual data. I don't understand what could be the reason. Any pointers please???
I want to dynamically resize my cells as data can be of random size. Data shows only after scrolling once.
This problem is related to using UITableViewAutomaticDimension and has been reported at other places as well. So this line of code, solved my problem:
-(void)viewDidAppear:(BOOL)animated {
[self.tableView reloadData];
}
This just reloads all the table sections and rows before displaying. So user does not experience blank rows. Refer: http://www.appcoda.com/self-sizing-cells/
You need to use reloadData in the main thread (viewDidLoad). You need to use
dispatch_async like the code below :
dispatch_async(dispatch_get_main_queue(), ^{
[self.mytable reloadData];
}
In setupTable, check sectionArray and orderedData to make sure they're not empty. Add an assertion in setupTable, e.g.,
sectionArray = [[SummaryModel sharedInstance] getTableSections:self.s_sendEnhancementServerDict];
orderedData = [[SummaryModel sharedInstance] getOrderedData:self.s_sendEnhancementServerDict];
NSAssert([sectionArray count] && [orderedData count], #"No data!"); // add this line
[self.bookingsTableView reloadData];
Swift 5+
IOS 13
Xcode 11.2.1 +
Amazing Answer
override func viewDidAppear(_ animated: Bool) {
// self.tablev.frame.origin.y = vnavigation.frame.maxY + 5
// tablevheight = self.tablev.frame.size.height
self.bgview.backgroundColor = UIColor.init(patternImage: UIImage(named: "chat_bg.png")!)
self.registerForKeyboardNotifications()
UIView.performWithoutAnimation {
tablev.beginUpdates()
tablev.endUpdates()
}
}
I've a TableView which is containing two variable on each row and it is refreshing every 2 seconds via getting data from the server. I want to change the labels colour every update if it is higher or lower in red or green. So please how can I do that? While I know how to change the label colour but don't know how to make the compression between each 2 seconds.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"comCell";
comTableViewCell *cell = (comTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
NSArray *parts = [[NSBundle mainBundle] loadNibNamed:#"comTableViewCell" owner:nil options:nil];
cell = [parts objectAtIndex:0];
}
id rowObject = [data1 objectAtIndex:indexPath.row];
[cell.lblType setText:[rowObject objectForKey:#"strSymbol"]];
[cell.lblOffer setText:[rowObject objectForKey:#"strOffer"]];
[cell.lblBid setText:[rowObject objectForKey:#"strBid"]];
cell.lblType.font = [UIFont fontWithName:#"Helvetica" size:12.0f];
cell.lblOffer.font = [UIFont fontWithName:#"Helvetica" size:12.0f];
cell.lblBid.font = [UIFont fontWithName:#"Helvetica" size:12.0f];
cell.lblType.textColor = [UIColor blackColor];
cell.lblOffer.textColor = [UIColor whiteColor];
cell.lblBid.textColor = [UIColor whiteColor];
return cell;
}
Data result:
{
strBid = "1.29158";
strOffer = "1.29258";
strSymbol = "USD/EUR";
},
{
strBid = "98.964";
strOffer = "99.004";
strSymbol = "AUD/JPY";
},
{
strBid = "11.2472";
strOffer = "11.2972";
strSymbol = "USD/ZAR";
}
Update:
data2 = data1;
id rowObject2 = [data2 objectAtIndex:indexPath.row];
NSString *new_offer = [rowObject2 objectForKey:#"strOffer"];
if (data2 != nil) {
id old_rowObject = [data2 objectAtIndex:indexPath.row];
NSString *old_offer = [old_rowObject objectForKey:#"strOffer"];
if ([new_offer doubleValue] > [old_offer doubleValue]) {
cell.lblOffer.textColor = [UIColor greenColor];
cell.lblBid.textColor = [UIColor greenColor];
}
else if ([new_offer doubleValue] == [old_offer doubleValue]) {
cell.lblOffer.textColor = [UIColor blackColor];
cell.lblBid.textColor = [UIColor blackColor];
}
else {
cell.lblOffer.textColor = [UIColor redColor];
cell.lblBid.textColor = [UIColor redColor];
}
} else {
// first time getting data.
}
return cell;
}
Update:
move this line data2 = data1; to the place you start parse the json. before the code you use to parse.
Old Post:
- (void)parserDidStartDocument:(NSXMLParser *)parser {
old_data = data1; <<-- saves data here!
data1 = [[…. alloc] init];
}
id rowObject = [data1 objectAtIndex:indexPath.row];
NSString *new_offer = [rowObject objectForKey:#"strOffer"];
if (old_data != nil) {
id old_rowObject = [old_data objectAtIndex:indexPath.row];
NSString *old_offer = [old_rowObject objectForKey:#"strOffer"];
if ([new_offer doubleValue] > [old_offer doubleValue]) {
// set colour here.
} else {
// and here.
}
} else {
// first time getting data.
}
I have added UISegmentedController to TableViewCell in CellForRowAtIndexPath.
Following is the code.
[cell.segStatus addTarget:self action:#selector(selectedSegmentControl:) forControlEvents: UIControlEventValueChanged];
[cell.segStatus setSegmentedControlStyle:UISegmentedControlStyleBar];
cell.segStatus.tag = indexPath.row;
I use UITableViewCell class for customized class.
I select segment and when I scroll the tableview some other cell's segmented controller also automatically select.
Why is it? how can I sort out this ?
Full CellForRowAtIndexPath Method
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
#try {
static NSString *defTableIdentifier = #"DefectRegisterCell";
DefectRegisterCell *cell = (DefectRegisterCell *)[self.tblDefectList dequeueReusableCellWithIdentifier:defTableIdentifier];
_defectEntry = [defectObjList objectAtIndex:indexPath.row];
cell.lblDefectNo.text = [NSString stringWithFormat:#"%#", _defectEntry.defectNo];
if ([_defectEntry.defect isEqual:#"None"] || [_defectEntry.defect isEqual:#""] ) {
cell.lblDefect.text = [NSString stringWithFormat:#"%# - %# - Passed", _defectEntry.item,_defectEntry.subItem];
}
else{
cell.lblDefect.text = [NSString stringWithFormat:#"%# - %# - %#", _defectEntry.item,_defectEntry.subItem,_defectEntry.defect];
}
cell.lblLocation.text = #"Location:";
cell.lblLocationValue.text = [NSString stringWithFormat:#"%# > %# > %# > %# (%# - %#)",_defectEntry.building, _defectEntry.area, _defectEntry.location, _defectEntry.room,_defectEntry.orient, _defectEntry.position];
cell.lblAssignedTo.text = #"Assigned to:";
cell.lblAssignedToValue.text = _defectEntry.responsibleComp;
cell.lblDue.text = #"Due:";
cell.lblDueValue.text = _defectEntry.dueDate;
cell.lblCapturedBy.text = #"Recorded by:";
cell.lblCapturedByValue.text = [NSString stringWithFormat:#"%# (%#)",_defectEntry.inspectedId,_defectEntry.inspectedCompId];
cell.lblDate.text = #"On:";
cell.lblDateValue.text = _defectEntry.createdDate;
NSString *attached = #"0" ;
NSString *fixClaimed = #"0";
NSString *completed = #"0";
if ([_defectEntry.attached length] > 0) {
attached = #"1";
}
if ([_defectEntry.fixClaimed isEqualToString:#"Y"]) {
fixClaimed = #"1";
}
if ([_common checkDateValidation:_defectEntry.completed]) {
completed = #"1";
}
[cell.segStatus addTarget:self action:#selector(selectedSegmentControl:) forControlEvents: UIControlEventValueChanged];
[cell.segStatus setSegmentedControlStyle:UISegmentedControlStyleBar];
cell.segStatus.tag = indexPath.row;
if ([attached isEqualToString:#"1"]) {
cell.imgAttachment.image = [UIImage imageNamed:#"diAttachments.png"];
}
if ([fixClaimed isEqualToString:#"1"]) {
cell.imgDefect.image = [UIImage imageNamed:#"diWarning.png"];
cell.segStatus.hidden = NO;
} else if ([completed isEqualToString:#"1"]) {
cell.imgDefect.image = [UIImage imageNamed:#"diRight.png"];
if ([_defectEntry.passed isEqualToString:#"Yes"]) {
cell.segStatus.hidden = YES;
}
else{
cell.segStatus.hidden = NO;
}
} else {
cell.imgDefect.image = [UIImage imageNamed:#"diWrong.png"];
cell.segStatus.hidden = NO;
}
UIView *backgroundView = [[UIView alloc] init];
if (indexPath.row % 2) {
backgroundView.backgroundColor = [UIColor whiteColor];
} else {
backgroundView.backgroundColor = [UIColor colorWithRed:242/255.0f green:242/255.0f blue:242/255.0f alpha:1.0f];
}
cell.backgroundView = backgroundView;
//change the selected cell color
UIView *selectedBackgroundView = [[UIView alloc] init];
selectedBackgroundView.backgroundColor = gaSelectedColor;
cell.selectedBackgroundView = selectedBackgroundView;
return cell;
}
#catch(NSException *excp)
{
NSLog(#"%#",excp);
}
}
As an example, I am trying to load a place name into my top UITableView, called myTableView. On the bottom, I am trying to display only "test2."
Naturally, all the data is being loaded into each UITableView. If I scroll to the bottom of myTableView2, the word "test2" IS shown, but I would like it to be the only thing there.
Is there a way, maybe by delegating different data sources, that I can separate the data I wan in each UITableView? I tried separating by if statements but quickly realized that had no effect.
It seems to me that I may need to set a separate datasource for myTableView2, but I am not sure how to do that...
Code is here:
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
[self setString];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
NSString *string1 = [dic objectForKey:#"name"];
for (NSDictionary *diction in dic)
{
[array addObject:string1];
}
[[self myTableView] reloadData];
NSString *string2 = [NSString stringWithFormat:#"test2"];
[array addObject:string2];
[[self myTableView2] reloadData];
[indicator stopAnimating];
indicator.hidden=YES;
[indicator removeFromSuperview];
ilabel.hidden = YES;
}
Solved with the code below. The key was to have two different arrays to load the respective data in, and display it at the very bottom where I am able to distinguish between UITableViews with IF statements:
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
[self setString];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
NSString *string1 = [dic objectForKey:#"name"];
NSString *string2 = [NSString stringWithFormat:#"test2"];
for (NSDictionary *diction in dic)
{
[array addObject:string1];
[array2 addObject:string2];
[[self myTableView] reloadData];
[[self myTableView2] reloadData];
}
[indicator stopAnimating];
indicator.hidden=YES;
[indicator removeFromSuperview];
ilabel.hidden = YES;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (tableView == self.myTableView)
{
if ([[array objectAtIndex:indexPath.row] isKindOfClass:[NSNumber class]])
{
cell.textLabel.text = [[array objectAtIndex:indexPath.row] stringValue];
cell.textLabel.textColor = [UIColor whiteColor];
cell.textLabel.textAlignment = NSTextAlignmentCenter;
}
else
{
cell.textLabel.text = [array objectAtIndex:indexPath.row];
cell.textLabel.textColor = [UIColor whiteColor];
cell.textLabel.textAlignment = NSTextAlignmentCenter;
}
}
if (tableView == self.myTableView2)
{
if ([[array2 objectAtIndex:indexPath.row] isKindOfClass:[NSNumber class]])
{
cell.textLabel.text = [[array2 objectAtIndex:indexPath.row] stringValue];
cell.textLabel.textColor = [UIColor whiteColor];
cell.textLabel.textAlignment = NSTextAlignmentCenter;
}
else
{
cell.textLabel.text = [array2 objectAtIndex:indexPath.row];
cell.textLabel.textColor = [UIColor whiteColor];
cell.textLabel.textAlignment = NSTextAlignmentCenter;
}
}
return cell;
}