UITableview load default selected values with checkmark in ios - ios

I have a method setting up value for table view for multi-selection row
- (id)initWithTitle:(NSString *)aTitle options:(NSArray *)aOptions matchingArray:(NSArray *)matchArray xy:(CGPoint)point size:(CGSize)size isMultiple:(BOOL)isMultiple
{
isMultipleSelection=isMultiple;
float height = MIN(size.height, DROPDOWNVIEW_HEADER_HEIGHT+[aOptions count]*44);
CGRect rect = CGRectMake(point.x, point.y, size.width, height);
if (self = [super initWithFrame:rect])
{
self.backgroundColor = [UIColor clearColor];
self.layer.shadowColor = [UIColor blackColor].CGColor;
self.layer.shadowOffset = CGSizeMake(2.5, 2.5);
self.layer.shadowRadius = 2.0f;
self.layer.shadowOpacity = 0.5f;
_kTitleText = [aTitle copy];
_kDropDownOption = #[#"India",#"Swaziland",#"Africa",#"Australlia",#"Pakistan",#"Srilanka",#"Mexico",#"United Kingdom",#"United States",#"Portugal"];
_kMatchingArray = #[#"United States",#"Swaziland"];
finalarray=[[NSMutableArray alloc]init];
for(int i = 0;i<[_kMatchingArray count];i++)
{
for(int j= 0;j<[_kDropDownOption count];j++)
{
if([[_kMatchingArray objectAtIndex:i] isEqualToString:[_kDropDownOption objectAtIndex:j]])
{
NSLog(#"%d",j);
NSString *str = [NSString stringWithFormat:#"%d",j];
[finalarray addObject:str];
}
else {
}
}
}
NSLog(#"finalArray:%#",finalarray);
// NSLog(#"%#",_kMatchingArray);
self.arryData=[[NSMutableArray alloc]init];
_kTableView = [[UITableView alloc] initWithFrame:CGRectMake(DROPDOWNVIEW_SCREENINSET,
DROPDOWNVIEW_SCREENINSET + DROPDOWNVIEW_HEADER_HEIGHT,
rect.size.width - 2 * DROPDOWNVIEW_SCREENINSET,
rect.size.height - 2 * DROPDOWNVIEW_SCREENINSET - DROPDOWNVIEW_HEADER_HEIGHT - RADIUS)];
_kTableView.separatorColor = [UIColor colorWithWhite:1 alpha:.2];
_kTableView.separatorInset = UIEdgeInsetsZero;
_kTableView.backgroundColor = [UIColor clearColor];
_kTableView.dataSource = self;
_kTableView.delegate = self;
[self addSubview:_kTableView];
if (isMultipleSelection) {
UIButton *btnDone=[UIButton buttonWithType:UIButtonTypeCustom];
[btnDone setFrame:CGRectMake(rect.origin.x+182,rect.origin.y-45, 82, 31)];
[btnDone setImage:[UIImage imageNamed:#"done#2x.png"] forState:UIControlStateNormal];
[btnDone addTarget:self action:#selector(Click_Done) forControlEvents: UIControlEventTouchUpInside];
[self addSubview:btnDone];
}
}
return self;
}
using this i have create a tableview fetching the values
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_kDropDownOption count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cel lForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentity = #"DropDownViewCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentity];
cell = [[DropDownViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentity];
NSInteger row = [indexPath row];
// NSIndexPath *selectedIndexPath = [finalarray addObject:indexPath.row];
UIImageView *imgarrow=[[UIImageView alloc]init ];
NSLog(#"aray:%#",self.arryData);
if([self.arryData containsObject:indexPath]){
imgarrow.frame=CGRectMake(230,2, 27, 27);
imgarrow.image=[UIImage imageNamed:#"check_mark#2x.png"];
} else
imgarrow.image=nil;
[cell addSubview:imgarrow];
cell.textLabel.text = [_kDropDownOption objectAtIndex:row] ;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if (isMultipleSelection) {
if([self.arryData containsObject:indexPath]){
[self.arryData removeObject:indexPath];
} else {
[self.arryData addObject:indexPath];
}
[tableView reloadData];
} else {
if (self.delegate && [self.delegate respondsToSelector:#selector(DropDownListView:didSelectedIndex:)]) {
[self.delegate DropDownListView:self didSelectedIndex:[indexPath row]];
}
// dismiss self
[self fadeOut];
}
}
I have two array one have total records of the tableview and another one have initially selected values.I have compare the two arrays and get matching indexpath. My problem was how to set check mark image on matched values row?

if ([_strProIDNS isEqualToString:strUNAssignNS])
{
tblViewCell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
tblViewCell.accessoryType = UITableViewCellAccessoryNone;

Related

iOS UItableviewCell clear old cell values

First of all sorry for asking this as I know there are a lot of questions which are similar to this. But so far nothing has worked for me. I have a table view with two buttons. On click of the button it loads two different custom cells. But I can't seem to clear out the old cell values no matter what I try. I have tried the prepareForReuse method to clear the old views but I end up with nothing displaying on the cells.
Here is the code that I am using.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if([[self.sections objectAtIndex:indexPath.section] count] > 0)
{
id object = [[self.sections objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
if (indexPath.section == self.sections.count-1)
{
if(self.CategoryButtonType == 0)
{
MediaListCarousel * cell = [self getMediaCellCarousel:object];
return cell;
}
else
{
NonMediaTableViewCell * cell = [self getNonMediaCell:object];
return cell;
}
}
else
{
//Do other stuff
}
}
return nil;
}
Here are the custom cells
-(NonMediaTableViewCell *)getNonMediaCell:(NSString *)name
{
NonMediaTableViewCell * cell = [self.tableView dequeueReusableCellWithIdentifier:nonmediaCellIdentifier];
if (cell == nil) {
cell = (NonMediaTableViewCell*)[VFHelper findCellWithClassName:[NonMediaTableViewCell class] nibName:#"NonMediaTableViewCell"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
[cell setNonMediaWithPackageName:name
delegate:self];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
return cell;
}
-(MediaListCarousel *)getMediaCellCarousel:(NSString *)name
{
MediaListCarousel * cell = [self.tableView dequeueReusableCellWithIdentifier:mediaCellIdentifier];
if (cell == nil) {
cell = (MediaListCarousel*)[VFHelper findCellWithClassName:[MediaListCarousel class] nibName:#"MediaListCarousel"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
[cell setUp:name delegate:self];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
return cell;
}
each of those custom cell has the prepareForReuse method as defined below.
- (void)prepareForReuse {
[super prepareForReuse];
// Clear contentView
BOOL hasContentView = [self.subviews containsObject:self.contentView];
if (hasContentView) {
for(UIView *subview in [self.contentView subviews])
{
[subview removeFromSuperview];
}
}
}
What happening when i add the removeFromSuperview in the prepareForReuse method I can empty view when I switch between the two views. If i dont use the prepareForReuse to remove the view I end up with views on top of each other when I click the different button. Can some one please help with this. Thanks in advance.
EDIT TO SHOW CUSTOM CELL CODE
-(void) getNonMediaCell:(NSString *)package
delegate:(NSObject <nonMediaCellDelegate> *)delegate
{
self.package = package;
[self loadValuefFromDB];
self.addonName = addonName;
_delegate = delegate;
[self.btnSeemore addTarget:self action:#selector(btnSeemoreClicked) forControlEvents:UIControlEventTouchUpInside];
if(_addons.isHidden)
{
_planDescTextView.hidden = YES;
_heightConstraintforPlanDescView.constant = 0;
_btnSeemore.imageView.transform = CGAffineTransformIdentity;
}
else
{
_planDescTextView.text = description;
CGSize neededSize = [_planDescTextView sizeThatFits:CGSizeMake(_planDescTextView.frame.size.width, CGFLOAT_MAX)];
_planDescTextView.hidden = NO;
_heightConstraintforPlanDescView.constant = neededSize.height + 5;
_btnSeemore.imageView.transform = CGAffineTransformMakeRotation(M_PI);
_btnSeemore.imageView.clipsToBounds = NO;
_btnSeemore.imageView.contentMode = UIViewContentModeCenter;
}
if(IsEmpty(addons.state))
{
_UIViewEntitlement.hidden = YES;
_UIViewBtnRepurchase.hidden = YES;
_seperatorView.hidden = YES;
[self resetCell];
[self setPriceLabelValue];
[self.purchaseBtn addTarget:self action:#selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside];
self.purchaseBtn.accessibilityLabel = [NSString stringWithFormat:#"%#_Purcahse", addonName];
self.purchaseBtn.accessibilityValue = [NSString stringWithFormat:#"%#_Purcahse", addonName];
self.purchaseBtn.accessibilityIdentifier = [NSString stringWithFormat:#"%#_Purcahse", addonName];
self.recurringIndicatorImageView.hidden = NO;
[self addOnRecurringIndicatorImages];
}
else
{
_UIViewEntitlement.hidden = NO;
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 20)];
VFAddonPlanentitlementCell * cell = (VFAddonPlanentitlementCell*)[VFHelper findCellWithClassName:[VFAddonPlanentitlementCell class] nibName:#"VFAddonPlanentitlementCell"];
[cell setFrame:CGRectMake(0, 0, self.frame.size.width, 20)];
if(!IsEmpty(_addons.remainingDays))
{
if(recurring || allowCancel)
{
if([[_addons.state uppercaseString] isEqualToString:#"ONHOLD"])
{
[cell setDaysRemainingColorWithTitleOnHold:#"Renews" daysRemainings:[_addons.remainingDays stringValue]];
}
else
{
[cell setRemainingColorWithTitle:#"Renews" daysRemainings:[_addons.remainingDays stringValue]];
}
}
else
{
[cell setDaysRemainingColorWithTitle:#"Time left" daysRemainings:[_addons.remainingDays stringValue]];
}
[headerView addSubview:cell];
}
[_UIViewEntitlement addSubview:headerView];
}
}
try this
-(void) getNonMediaCell:(NSString *)package
delegate:(NSObject <nonMediaCellDelegate> *)delegate
{
.....//other code
UIView *headerView = [_UIViewEntitlement viewWithTag:12345];
if(headerView == nil) {
headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 20)];
[headerView setTag:12345];//set tag
} else {
NSLog(#"headerView already exist");
}
//set values
.....//other code
}
and in reuse method
- (void)prepareForReuse {
[super prepareForReuse];
UIView *header = [_UIViewEntitlement viewWithTag:12345];//use same tag
[header removeFromSuperview];
}
if you are creating and adding multiple views programatically, then set tag to each views and remove those in reuse by accessing it with same tag value.

How to expand and collapse UITableview cell sections on navigation bar button click action

Please look at the code:
ViewControlller.h
#property (nonatomic, strong) IBOutlet UITableView *tablevw;
#property (nonatomic , strong) IBOutlet UIButton *minusBtn;
-(IBAction)minusBtnAction:(id)sender;
ViewController.m
#interface ViewController ()
{
NSArray *sectionTitleArray;
NSMutableArray *arrayForBool;
NSArray *applesArray;
NSArray *grapesArray;
UIButton *button;
int clickedIndex;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_tablevw.delegate = self;
_tablevw.dataSource =self;
_tablevw.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
_tablevw.separatorStyle = UITableViewCellSeparatorStyleNone;
[UIView setAnimationsEnabled:NO];
arrayForBool = [[NSMutableArray alloc]init];
clickedIndex = 0;
sectionTitleArray = #[ #{#"text": #"Apples"},
#{#"text": #"Grapes"},
];
applesArray = #[ #{#"text1": #"Apple1"},
#{#"text1": #"Apple2"},
#{#"text1": #"Apple3"},
#{#"text1": #"Apple4"},
#{#"text1": #"Apple5"},
#{#"text1": #"Apple6"},
#{#"text1": #"Apple7"},
#{#"text1": #"Apple8"},
];
grapesArray = #[ #{#"text2": #"Grapes1"},
#{#"text2": #"Grapes2"},
#{#"text2": #"Grapes3"},
#{#"text2": #"Grapes4"},
#{#"text2": #"Grapes5"},
#{#"text2": #"Grapes6"},
#{#"text2": #"Grapes7"},
#{#"text2": #"Grapes8"},
];
for (int i=0; i<[sectionTitleArray count]; i++)
{
[arrayForBool addObject:[NSNumber numberWithBool:NO]];
}
}
#pragma mark:- UITableView Delegate and Datasource Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return sectionTitleArray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([[arrayForBool objectAtIndex:section] boolValue])
{
if (section == 0)
{
return [applesArray count];
}
else if (section == 1)
{
return [grapesArray count];
}
}
return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
cell.textLabel.textColor = [UIColor purpleColor];
if (cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
BOOL manyCells = [[arrayForBool objectAtIndex:indexPath.section]boolValue];
if (!manyCells)
{
cell.backgroundColor = [UIColor clearColor];
cell.textLabel.text = #"";
}
else
{
if (indexPath.section == 0)
{
cell.textLabel.text = [[applesArray objectAtIndex:indexPath.row]objectForKey:#"text1"];
}
else if (indexPath.section == 1)
{
cell.textLabel.text = [[grapesArray objectAtIndex:indexPath.row]objectForKey:#"text2"];
}
}
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
/*************** Close the section, once the data is selected ***********************************/
[arrayForBool replaceObjectAtIndex:indexPath.section withObject:[NSNumber numberWithBool:NO]];
[_tablevw reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationAutomatic];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([[arrayForBool objectAtIndex:indexPath.section] boolValue])
{
return 40;
}
return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 40;
}
#pragma mark - Creating View for TableView Section
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *sectionView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 280,40)];
sectionView.tag=section;
UILabel *viewLabel=[[UILabel alloc]initWithFrame:CGRectMake(13, 0, _tablevw.frame.size.width-10, 40)];
viewLabel.backgroundColor=[UIColor clearColor];
viewLabel.font=[UIFont systemFontOfSize:15];
viewLabel.text= [[sectionTitleArray objectAtIndex:section] objectForKey:#"text"];
viewLabel.textColor=[UIColor purpleColor];
[sectionView addSubview:viewLabel];
/********** Add a custom Separator with Section view *******************/
UIView* separatorLineView = [[UIView alloc] initWithFrame:CGRectMake(12, 40, _tablevw.frame.size.width-35, 1)];
separatorLineView.backgroundColor = [UIColor purpleColor];
[sectionView addSubview:separatorLineView];
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:#"Add_plus_iCon_iphone_4s"] forState:UIControlStateNormal];
button.frame = CGRectMake(sectionView.frame.size.width-10, 10, 20, 20);
[sectionView addSubview:button];
/********** Add UITapGestureRecognizer to SectionView **************/
UITapGestureRecognizer *headerTapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(sectionHeaderTapped:)];
[sectionView addGestureRecognizer:headerTapped];
return sectionView;
}
#pragma mark - Table header gesture tapped
- (void)sectionHeaderTapped:(UITapGestureRecognizer *)gestureRecognizer
{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:gestureRecognizer.view.tag];
if (indexPath.row == 0)
{
BOOL collapsed = [[arrayForBool objectAtIndex:indexPath.section] boolValue];
for (int i=0; i<[sectionTitleArray count]; i++)
{
if (indexPath.section==i)
{
[arrayForBool replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:!collapsed]];
}
}
[_tablevw reloadSections:[NSIndexSet indexSetWithIndex:gestureRecognizer.view.tag] withRowAnimation:UITableViewRowAnimationAutomatic];
}
if (clickedIndex == 0)
{
clickedIndex++;
[button setImage:[UIImage imageNamed:#"Add_minus_iCon_iphone_4s"] forState:UIControlStateNormal];
}
else
{
clickedIndex = 0;
[button setImage:[UIImage imageNamed:#"Add_plus_iCon_iphone_4s"] forState:UIControlStateNormal];
}
[_tablevw reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}
-(IBAction)minusBtnAction:(id)sender
{
if (clickedIndex == 0)
{
clickedIndex++;
[_minusBtn setImage:[UIImage imageNamed:#"ic_minus"] forState:UIControlStateNormal];
}
else
{
clickedIndex = 0;
[_minusBtn setImage:[UIImage imageNamed:#"ic_plus"] forState:UIControlStateNormal];
}
}
I'm having two rows in tableview whenever I am tapping the + button the objects in applesArray are expanding and collapsing. By default + symbol will display on every cell. If I tap for first the button will change to - and tableview cells will expand.
Like the same way in my navigation bar I am having ic_minus image with button background. When the button is in ic_minus state all sections should display normal i.e Apples and Grapes should display.
After, when I click on the ic_minus button it should change into ic_plus image and all sections should expand with their row objects like Apples with apple1, apple2......apple8 should expand and same as with grapesArray also.

How to populate, Expandable TableView with two NSMutableArray using objective-c

I am using an Expandable UITableview created by Tom Fewster. I want to tweak the example using two NSMutableArrays, which is a scenario whereby if someone wants to populate an expandable/collapse treeview table from webservice json data would want to achieve. So since in his example the GroupCell does not have an array of, I am wondering how can I do it? Please bear in mind that my Objective-C is still rusty hence, I'm asking this question.
With my attempt is only displaying the first ObjectAtIndex:indexPath:0 for the group.
I want to be able to populate the table and get output like this;
Group A
Row 1a
Row 2a
Row 3a
Group B
Row 1b
Row 2b
Group C
Row 1c
Row 2c
Row 3c
and so on.
You may use JSON data as well to explain your answer if you understand it better that way.
Here i want to populate the table with JSON data so the GroupCell show class_name and rowCell show subject_name. This is the console of what I am parsing from the JSON web-service;
(
{
"class_id" = 70;
"class_name" = Kano;
subject = (
"subject_id" = 159;
"subject_name" = "Kano Class";
}
);
},
{
"alarm_cnt" = 0;
"class_id" = 71;
"class_name" = Lagos;
subject = (
"subject_id" = 160;
"subject_name" = "Lagos Class";
}
);
},
{
"alarm_cnt" = 3;
"class_id" = 73;
"class_name" = Nasarawa;
subject = (
"subject_id" = 208;
"subject_name" = "DOMA Class";
},
"subject_id" = 207;
"subject_name" = "EGGON Class";
},
"subject_id" = 206;
"subject_name" = "KARU Class";
},
"subject_id" = 209;
"subject_name" = "LAFIA Class";
},
"subject_id" = 161;
"subject_name" = "Nasarawa State Class";
}
);
},
{
"alarm_cnt" = 2;
"class_id" = 72;
"class_name" = Rivers;
subject = (
"subject_id" = 162;
"subject_name" = "Rivers Class";
}
);
}
)
I have tried this here is my snippet
- (UITableViewCell *)tableView:(ExpandableTableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"RowCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSDictionary *d=[_sitesJson objectAtIndex:0] ;
NSArray *arr=[d valueForKey:#"subject_name"];
NSDictionary *subitems = [arr objectAtIndex:0];
NSLog(#"Subitems: %#", subitems);
NSString *siteName = [NSString stringWithFormat:#"%#",subitems];
cell.textLabel.text =siteName;
//}
NSLog(#"Row Cell: %#", cell.textLabel.text);
// just change the cells background color to indicate group separation
cell.backgroundView = [[UIView alloc] initWithFrame:CGRectZero];
cell.backgroundView.backgroundColor = [UIColor colorWithRed:232.0/255.0 green:243.0/255.0 blue:1.0 alpha:1.0];
return cell;
}
- (UITableViewCell *)tableView:(ExpandableTableView *)tableView cellForGroupInSection:(NSUInteger)section
{
static NSString *CellIdentifier = #"GroupCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UILabel *textLabel = (UILabel *)[cell viewWithTag:2];
NSDictionary *d2 = [_regionsJson objectAtIndex:0];
NSArray *arr2 = [d2 objectForKey:#"class_name"];
NSString *regions = [[arr2 objectAtIndex:section]objectAtIndex:0];
textLabel.textColor = [UIColor whiteColor];
textLabel.text = [NSString stringWithFormat: #"%# (%d)", regions, (int)[self tableView:tableView numberOfRowsInSection:section]];
NSLog(#"Group cell label: %#", textLabel.text);
// We add a custom accessory view to indicate expanded and colapsed sections
cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"ExpandableAccessoryView"] highlightedImage:[UIImage imageNamed:#"ExpandableAccessoryView"]];
UIView *accessoryView = cell.accessoryView;
if ([[tableView indexesForExpandedSections] containsIndex:section]) {
accessoryView.transform = CGAffineTransformMakeRotation(M_PI);
} else {
accessoryView.transform = CGAffineTransformMakeRotation(0);
}
return cell;
}
He, just need to update one single method little bit way
- (UITableViewCell *)tableView:(ExpandableTableView *)tableView cellForGroupInSection:(NSUInteger)section
{
static NSString *CellIdentifier = #"GroupCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSIndexPath *indexPath;
NSString *regions = [[_dataGroup objectAtIndex:section]objectAtIndex:0];
cell.textLabel.text = [NSString stringWithFormat: #"%# ", regions];
// We add a custom accessory view to indicate expanded and colapsed sections
cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"ExpandableAccessoryView"] highlightedImage:[UIImage imageNamed:#"ExpandableAccessoryView"]];
UIView *accessoryView = cell.accessoryView;
if ([[tableView indexesForExpandedSections] containsIndex:section]) {
accessoryView.transform = CGAffineTransformMakeRotation(M_PI);
} else {
accessoryView.transform = CGAffineTransformMakeRotation(0);
}
return cell;
}
May help it you.
HTH, Enjoy Coding !!
I think you need to create a TableView which will have a sections array, and each sections row will be populated using the corresponding sections array. Tapping on a section will expand it and it's all rows will be visible.
To meet your requirements, you could follow the below steps as well -
1) Your modal should have a array for sections. The sections array will contain the sections objects, name of the section and corresponding array of the rows.
2) Implement the data source methods of the table view like
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return [section count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 50; // sections height
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return nil;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0 , 0, tableView.frame.size.width , 50)] autorelease];
[view setBackgroundColor:[UIColor redColor]];
view.layer.masksToBounds = YES;
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5 , 2 , view.frame.size.width - 10 , view.frame.size.height - 3)];
label.text = ((SectionObject *)[section objectAtIndex:indexPath.section]).sectionName;
label.backgroundColor = [UIColor clearColor];
label.textAlignment = NSTextAlignmentLeft;
label.textColor = [UIColor WwhiteColor];
label.clipsToBounds = YES;
label.font = [UIFont fontWithName:#"HelveticaNeue-CondensedBold" size:14.0f];
label.layer.masksToBounds = YES;
UIImageView *arrowImage = [[UIImageView alloc] initWithFrame:CGRectMake(view.frame.size.width - 30, 0, 17 , 17)];
[arrowImage setCenter:CGPointMake(arrowImage.center.x , (view.frame.size.height/2) ) ];
if(section == self.m_currentSelectedSection)
[arrowImage setImage:self.m_upArrowImage];
else
[arrowImage setImage:self.m_downArrowImage];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, view.frame.size.width, view.frame.size.height)];
button.tag = section;
[button addTarget:self action:#selector(sectionTapped:) forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor = [UIColor clearColor];
[view addSubview:label];
[label release];
[view addSubview:arrowImage];
[arrowImage release];
[view addSubview:button];
[button release];
view.clipsToBounds = YES;
return view;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger count = 0;
if(self.m_currentSelectedSection == section)
count = [((SectionObject *)[section objectAtIndex:indexPath.section]).rowArray count];
return count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 40.0;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * cellId = #"cellIdentifier";
UITableViewCell *cell = nil;
cell = (UITableViewCell *) [tableView dequeueReusableCellWithIdentifier:cellId];
if(cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
//customize cell
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:NO];
}
When ever any section will be tapped following event will be invoked
- (void) sectionTapped:(UIButton *)button
{
self.m_currentSelectedSection = button.tag;
[self performSelector:#selector(refreshView) withObject:nil afterDelay:POINT_ONE_SECOND];
if(m_winnerSlotList->at(self.m_currentSelectedSection).m_leaderboardList.size())
[self.m_leaderboardTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:button.tag] atScrollPosition:UITableViewScrollPositionTop animated:YES];
UIView *baseView = [button superview];
if(baseView)
{
for(int ii = 0 ; ii < [[baseView subviews] count] ; ii++ )
{
UIView *anyView = [[baseView subviews] objectAtIndex:ii];
if([anyView isKindOfClass:[UIImageView class]])
[(UIImageView *)anyView setImage:self.m_upArrowImage];
}
}
}
Initialize self.m_currentSelectedSection = 0, for the first time, this will show the rows for 0th section. As any section is tapped it's rows will be visible (corresponding section rows will expand) and the rows for the previous selected section will be hidden(previous section rows will collapse).
If you need to show more than one section as expanded than you need to keep track of all the section whether a section is expanded or not and accordingly load show/ hide the cells for the corresponding section.

UILabel showing wrong

i'm using a tableview to load datas from my college db, the table load the tablecell normally... but when i scroll down the table the name of the discipline goes well but the grade is showing up one on top of above
why is that?
#import "NFMainViewController.h"
#import "NFData.h"
#interface NFMainViewController ()
#end
#implementation NFMainViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
data = [[NFData getData] objectForKey:#"data"];
cursoData = nil;
cursosView = [[UIViewController alloc] init];
[cursosView setTitle:#"Cursos"];
cursosTable = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds];
[cursosTable setDelegate:self];
[cursosTable setDataSource:self];
[cursosView.view addSubview:cursosTable];
[self pushViewController:cursosView animated:NO];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - TableView delegates
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (tableView == cursosTable) {
return [data count];
} else {
return [cursoData count];
}
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
static NSString *ident = #"headerIdent";
UITableViewHeaderFooterView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:ident];
if (view == nil) {
view = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:ident];
}
if (tableView == cursosTable) {
view.textLabel.text = [[data objectAtIndex:section] objectForKey:#"unidade"];
} else {
NSDictionary *temp = [cursoData objectAtIndex:section];
view.textLabel.text = [NSString stringWithFormat:#"%#ยบ/%#", [temp objectForKey:#"semestre"], [temp objectForKey:#"ano"]];
}
return view;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == cursosTable) {
return [[[data objectAtIndex:section] objectForKey:#"cursos"] count];
} else {
return [[[cursoData objectAtIndex:section] objectForKey:#"disciplinas"] count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *ident = #"cellIdent";
UITableViewCell *view = [tableView dequeueReusableCellWithIdentifier:ident];
if (view == nil) {
view = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ident];
}
if (tableView == cursosTable) {
view.textLabel.text = [[[[data objectAtIndex:indexPath.section] objectForKey:#"cursos"] objectAtIndex:indexPath.row] objectForKey:#"curso"];
} else {
UIFont *font = [UIFont fontWithName:#"Arial" size:10.0f];
view.textLabel.font = font;
view.selectionStyle = UITableViewCellSelectionStyleNone;
NSDictionary *temp = [[[cursoData objectAtIndex:indexPath.section] objectForKey:#"disciplinas"] objectAtIndex:indexPath.row];
view.textLabel.text = [temp objectForKey:#"disciplina"];
CGRect notaRect = view.bounds;
notaRect.origin.x = notaRect.size.width - 70.0f;
notaRect.size.width = 50.0f;
UILabel *nota = [[UILabel alloc] initWithFrame:notaRect];
nota.textAlignment = NSTextAlignmentRight;
nota.font = font;
nota.text = [temp objectForKey:#"nota"];
[view addSubview:nota];
CGRect labelRect = view.textLabel.frame;
labelRect.size.height -= 60;
view.textLabel.frame = labelRect;
CGRect progRect = view.bounds;
progRect.origin.x += 6.0f;
progRect.size.width -= 12.0f;
progRect.origin.y += progRect.size.height - 6.0f;
progRect.size.height = 5.0f;
UIProgressView *prog = [[UIProgressView alloc] initWithFrame:progRect];
int faltas = [[temp objectForKey:#"faltas"] intValue];
int maximo = [[temp objectForKey:#"maximo"] intValue];
float value = 1.0f * faltas / maximo;
if (value > 1.0f) {
prog.progressTintColor = [UIColor blackColor];
} else if (value == 1.0f) {
prog.progressTintColor = [UIColor redColor];
} else if (value >= 0.7f) {
prog.progressTintColor = [UIColor yellowColor];
}
[prog setProgress:value];
[view addSubview:prog];
}
return view;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (tableView == cursosTable) {
cursoData = [[[[data objectAtIndex:indexPath.section] objectForKey:#"cursos"] objectAtIndex:indexPath.row] objectForKey:#"epocas"];
notasView = [[UIViewController alloc] init];
[notasView setTitle:#"Disciplinas"];
notasTable = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds];
[notasTable setDelegate:self];
[notasTable setDataSource:self];
[notasView.view addSubview:notasTable];
[self pushViewController:notasView animated:YES];
}
}
#end
Your nota UILabel is created each time a UITableViewCell is dequeued. So the first time the tableview loads everything is fine. Then when you start scrolling, your code reuse cells with the nota label already created, but you add another label on top of it. You need to reuse the label previously created.
The best way is to create a UITableViewCell subclass with a nota property for instance.

Segmented Control change tableView datasource

UISegmentedControl changes tableView datasource.
After I described [myView addSubview:_tableView];
instead of [self.view addSubview:_tableView];,
daySegmentedControl process stopped working.
I have this code.
ViewController.m
#implementation ViewController
{
int _tableType;
NSArray *_data1;
NSArray *_data2;
}
#synthesize segment;
#synthesize daySegment;
#synthesize myView;
- (void)viewDidLoad
{
[super viewDidLoad];
_tableType = 1;
_data1 = #[#[#"A",#"B",#"C"]];
_data2 = #[#[#"D",#"E",#"F"]];
myView = [[UIView alloc]initWithFrame:CGRectMake(-1, 44, 340, 480)];
[self.view addSubview:myView];
myView.opaque = NO;
myView.backgroundColor = [UIColor colorWithWhite:1.0f alpha:0.0f];
[self.view bringSubviewToFront:myView];
[self segmentView];
[self daySegmentView];
[self dayTableView];
}
- (void)segmentView
{
NSArray *SegmentContent = [NSArray arrayWithObjects:#"View1",#"View2",nil];
segment = [[UISegmentedControl alloc] initWithItems:WDSegmentContent];
segment.frame = CGRectMake(-2, 20, 326, 25);
segment.selectedSegmentIndex = 0;
[segment addTarget:self action:#selector(WDSegmentAction:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:segment];
}
- (void)WDSegmentAction:(id)sender
{
switch (segment.selectedSegmentIndex){
case 0:
[self dayTableView];
break;
case 1:
[self dayTableView];
break;
default:
break;
}
}
- (void)daySegmentView
{
NSArray *daySegmentContent = [NSArray arrayWithObjects:#"A",#"D",nil];
daySegment = [[UISegmentedControl alloc] initWithItems:daySegmentContent];
daySegment.frame = CGRectMake(0, 0, 326, 25);
daySegment.selectedSegmentIndex = 0;
[daySegment addTarget:self action:#selector(daySegmentAction:) forControlEvents:UIControlEventValueChanged];
[myView addSubview:daySegment];
}
- (void)daySegmentAction:(id)sender
{
switch (segment.selectedSegmentIndex){
case 0:
_tableType = 1;
[self.tableView reloadData];
break;
case 1:
_tableType = 2;
[self.tableView reloadData];
break;
default:
break;
}
}
- (void)dayTableView
{
_tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 30, 320, 480)];
_tableView.dataSource = self;
_tableView.delegate = self;
[myView addSubview:_tableView];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_data1[section]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];
}
NSString *data;
if (_tableType == 1) {
data = _data1[indexPath.section][indexPath.row];
} else if (_tableType == 2){
data = _data2[indexPath.section][indexPath.row];
}
cell.textLabel.text = data;
return cell;
}
#end
Any idea on how I could fix it?
I used different approach for changing segments. Just for illustration:
in segment changed method:
[_tableView reloadData];
In your numberOfRowsInSection:
if(_segControl.selectedSegmentIndex == 0)
{
return [dataSourceOne count];
}else
{
return [dataSourceTwo count];
}
}
In your heightForRowAtIndexPath
if(_segControl.selectedSegmentIndex == 0) { //one
return 60;
} else { //two
return 70;
}
In your cellForRowAtIndexPath
if(_segControl.selectedSegmentIndex == 0) {
//generate and populate cell for type one
}else
{
//generate and populate cell for type two
}
Use daySegment.selectedSegmentIndex instead of segment.selectedSegmentIndex in
- (void)daySegmentAction:(id)sender

Resources