I have taken section with title let say
Monday,Tuesday,Wednesday......Sunday etc.also I have added "+" button after section title & added action on that button
Below is code and screenshot.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return [SectionArray count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if (section ==0) {
return 0;
}else{
return 3;
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [SectionArray objectAtIndex:section];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
CGRect frame = tableView.frame;
UIView *headerView;
if(section == 0 || section == 7) {
}else{
UIButton *addButton=[UIButton buttonWithType:UIButtonTypeContactAdd];
addButton.frame =CGRectMake(frame.size.width-60, 5, 50,30);
addButton.titleLabel.text = #"+";
addButton.tag =section;
// addButton.backgroundColor = [UIColor grayColor];
[addButton addTarget:self action:#selector(AddTimeSlot:) forControlEvents:UIControlEventTouchUpInside];
UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(30, 10, 100, 30)];
title.text = [SectionArray objectAtIndex:section];
headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
[headerView addSubview:title];
[headerView addSubview:addButton];
}
return headerView;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *cellIdent = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdent];
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdent];
}
return cell;
}
now i have to create cell when i click on "+" button,so please help me .
You can do that as below,
First you have to use an array for the data source that would be manipulated dynamically.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if (section ==0) {
return 0;
}else{
return numberOfRowNeedToDisplay; //Take global int variable
}
}
In your button action AddTimeSlot:
-(void)addTimeSlot:(id)sender {
//If you want to add cell to section
NSMutableArray *arrayIndexPathsToBeAdded = [[NSMutableArray alloc] init];
for (int i = 0; i < <numberOfCellsYouWantToAdd>; i++) {
[arrayIndexPathsToBeAdded addObject:[NSIndexPath indexPathForRow:i inSection:view.tag]];
}
numberOfRowNeedToDisplay = <numberOfCellsYouWantToAdd>;
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:arrayIndexPathsToBeAdded withRowAnimation:UITableViewRowAnimationRight];
[self.tableView endUpdates];
//If you want to remove cells
NSMutableArray *arrayIndexPathsToBeRemoved = [[NSMutableArray alloc] init];
for (int i = 0; i < <numberOfCellsYouWantToRemove>; i++) {
[arrayIndexPathsToBeRemoved addObject:[NSIndexPath indexPathForRow:i inSection:sectionIndexToBeExpanded]];
}
numberOfRowNeedToDisplay = <numberOfCellsYouWantToRemove>;
[self.tableView beginUpdates];
[self.tableView deleteRowsAtIndexPaths:arrayIndexPathsToBeRemoved withRowAnimation:UITableViewRowAnimationLeft];
}
This is what i have had done:
Please read commented text.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
/** should be change in dynamically
maintain array for every section rows
return row count accordint to section
**/
}
#pragma mark - Private methods
- (void)AddTimeSlot:(UIButton *)sender {
int sectionNo = sender.tag;
// Get you section rowArray(DATASOURCE) and insert you detaisl
// then add UI
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[tableView beginUpdates];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
[tableView endUpdates];
}
Related
I have been playing around with this problem since a day and I have tried many ways to resolve this issue but have not yet succeeded. I have a tableview with 3 custom cells and I have added section header for last two sections. Here is the screen shot.
which shows last section header is repeating when I enter text in the TextView. My TextView is editable and I have disabled the scrolling to adjust the size of the textview as per the text size.
Here is the code.
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 3;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSArray *titleArray = #[#"",#"About You",#"Gender"];
NSString *titleHeading = [titleArray objectAtIndex:section];
return titleHeading;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return section == 0 ? CGFLOAT_MIN : 35;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *identifier = [NSString stringWithFormat:#"cell%ld,%ld",indexPath.section, indexPath.row];
id cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (indexPath.section == 1)
{
ProfileAboutCell *cellObj = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cellObj)
{
[_tableView registerNib:[UINib nibWithNibName:#"ProfileAboutCell" bundle:nil] forCellReuseIdentifier:identifier];
cellObj = [tableView dequeueReusableCellWithIdentifier:identifier];
}
cellObj.selectionStyle = UITableViewCellSelectionStyleNone;
//[cellObj.txtAboutYou layoutIfNeeded];
cellObj.txtAboutYou.delegate = self;
cellObj.lbl = [[UILabel alloc] initWithFrame:CGRectMake(5.0, 0.0,cellObj.txtAboutYou.frame.size.width - 10.0, 34.0)];
cellObj.lbl.text = #"About You";
[cellObj.lbl setBackgroundColor:[UIColor clearColor]];
[cellObj.lbl setTextColor:[UIColor lightGrayColor]];
[cellObj.txtAboutYou addSubview:cellObj.lbl];
// [cellObj.txtAboutYou setText:[kUserDefaults valueForKey:kAbout]];
//[cellObj.txtAboutYou sizeToFit];
cell = cellObj;
}
return cell;
}
TextView Delegate Method.
-(void)textViewDidChange:(UITextView *)textView
{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
ProfileAboutCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
if(![textView hasText]) {
cell.lbl.hidden = NO;
}
else{
cell.lbl.hidden = YES;
}
NSInteger len = textView.text.length;
cell.lblChar.text=[NSString stringWithFormat:#"%li",500-len];
[_tableView beginUpdates];
[_tableView endUpdates];
}
I have tried this #SO solution but no help. Any help would be much appreciated in this direction. Thanks in advance.
From my understanding of the issue you can solve it by set the sections headers in "titleForHeaderInSection" the same way you set the cells in "cellForRowAtIndexPath" for each section,
this way sections that you don't set Headers for will not cause any issue.
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSArray *titleArray = #[#"",#"About You",#"Gender"];
if (indexPath.section == 1) {
NSString *titleHeading = [titleArray objectAtIndex:1];
return titleHeading;
}
if (indexPath.section == 2) {
NSString *titleHeading = [titleArray objectAtIndex:2];
return titleHeading;
}
}
So i have been trying for a little while now to create a table view with expandable sections and one non expandable section. One of the expandable sections should have 3 text fields inside them in which you can edit the test inside the text field. I was able to get that working bt the moment you collapse the section and expand it again the textfield suddenly duplicates itself above and sometimes swaps itself out with the above cell. Ihavent been able to figure out why or how to make it not do that.
The idea is when the user enters text in the field and selects enter the text is stored into an array.
the code:
- (void)viewDidLoad{
[super viewDidLoad];
if (!expandedSections){
expandedSections = [[NSMutableIndexSet alloc] init];
}
manualSensorName = [[NSMutableArray alloc]initWithObjects: #"Sensor",#"",#"2",#"T", nil];
}
- (void)didReceiveMemoryWarning{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Expanding
- (BOOL)tableView:(UITableView *)tableView canCollapseSection:(NSInteger)section{
if (section>0) return YES;
return NO;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if ([self tableView:tableView canCollapseSection:section])
{
if ([expandedSections containsIndex:section])
{
return 5; // return rows when expanded
}
return 1; // only top row showing
}
// Return the number of rows in the section.
return 1;
}
- (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];
}
// Configure the cell...
if ([self tableView:tableView canCollapseSection:indexPath.section]){
if (!indexPath.row){
// first row
cell.textLabel.text = #"Expandable"; // only top row showing
if ([expandedSections containsIndex:indexPath.section])
{
UIImageView *arrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"arrowUP.png"]];
cell.accessoryView = arrow;
}
else
{
UIImageView *arrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"arrowDOWN.png"]];
cell.accessoryView = arrow;
}
}
else {
if (indexPath.row == 1){
NSString *flightNumText = [manualSensorName objectAtIndex:indexPath.row];
cell.textLabel.text = flightNumText;
}
else if (indexPath.row == 2){
txtManualSensor = [[UITextField alloc] initWithFrame:CGRectMake(180, 5, 120, 30)];
txtManualSensor.placeholder = #"Select";
txtManualSensor.delegate = self;
txtManualSensor.autocorrectionType = UITextAutocorrectionTypeNo;
txtManualSensor.backgroundColor = [UIColor whiteColor];
[txtManualSensor setBorderStyle:UITextBorderStyleBezel];
[txtManualSensor setTextAlignment:NSTextAlignmentCenter];
[txtManualSensor setReturnKeyType:UIReturnKeyDone];
// UITextField *playerTextField = [[UITextField alloc] initWithFrame:CGRectMake(180, 5, 120, 30)];
// playerTextField.adjustsFontSizeToFitWidth = YES;
// playerTextField.textColor = [UIColor blackColor];
// playerTextField.placeholder = #"SAMPLE";
// playerTextField.tag = 200;
// playerTextField.delegate = self;
// [cell.contentView addSubview:playerTextField];
cell.textLabel.text = #"Sensor Name";
[cell addSubview:txtManualSensor];
}
else if (indexPath.row == 3){
cell.textLabel.text = #"Some Detail";
cell.accessoryView = nil;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
}
}
else {
cell.accessoryView = nil;
cell.textLabel.text = #"Normal Cell";
}
return cell;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
[manualSensorName replaceObjectAtIndex:2 withObject:textField.text];
return YES;
}
-(BOOL) textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if ([self tableView:tableView canCollapseSection:indexPath.section]){
if (!indexPath.row){
[tableView beginUpdates];
// only first row toggles exapand/collapse
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSInteger section = indexPath.section;
BOOL currentlyExpanded = [expandedSections containsIndex:section];
NSInteger rows;
NSMutableArray *tmpArray = [NSMutableArray array];
if (currentlyExpanded) {
rows = [self tableView:tableView numberOfRowsInSection:section];
[expandedSections removeIndex:section];
}
else {
[expandedSections addIndex:section];
rows = [self tableView:tableView numberOfRowsInSection:section];
}
for (int i=1; i<rows; i++) {
NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i inSection:section];
[tmpArray addObject:tmpIndexPath];
}
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (currentlyExpanded) {
UIImageView *arrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"arrowDOWN.png"]];
[tableView deleteRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationFade];
cell.accessoryView = arrow;
}
else {
UIImageView *arrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"arrowUP.png"]];
[tableView insertRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationFade];
cell.accessoryView = arrow;
}
NSLog(#"tableview row is %ld in section %ld",(long)indexPath.row,(long)indexPath.section);
[tableView endUpdates];
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSLog(#"selected row is %ld in section %ld",(long)indexPath.row,(long)indexPath.section);
if (indexPath.row == 1) {
// update text fields in cell table view
}
}
}
It may be as simple as replacing UITableViewRowAnimationTop by UITableViewRowAnimationFade:
When changing indexes in didSelectRowAtIndexPath, UITableViewCells change physical location (remember that the UITableView is a UIScrollView), and the scroller can't keep track of what your intent is.
UITableViewRowAnimationTop attempts to adjust the scrolling location, but fails.
Other design considerations:
Do not mix the model (the array of data to be displayed) with your view model (the UI displaying the model). In didSelectRowAtIndexPath, you should first re-order your model, then apply it to the cells
Consider not changing indexes on the fly: you may prefer a model that actually reflects the view structure, i.e. a tree.
Have you noticed you are not respecting - (void)tableView:(UITableView *)tableView and sometimes using self tableView:tableView or self.customTableView in the same method? You should use the tableView passed to you.
I am loading a UIWebview in a expand/collapse UITableView. I need to change the row height according to the UIWebview content height. if i set the UIWebview delegate in the UITableview, the UIWebview delgate method keeps get calling over and over. i am calling the webviewDidFinishLoad method to get the content height. Any kind of help/suggestion would be very appreciative.
- (BOOL)tableView:(UITableView *)tableView canCollapseSection:(NSInteger)section
{
return YES;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.restauRantMenuArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([self tableView:self.restaurantMenuTableView canCollapseSection:section])
{
if ([expandedSections containsIndex:section])
{
return 2; // return rows when expanded
}
return 1; // only top row showing
}
// Return the number of rows in the section.
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self tableView:self.restaurantMenuTableView canCollapseSection:indexPath.section])
{
if (indexPath.row == 0)
{
static NSString *MyIdentifier = #"menuTitleCell";
RestaurantMenuTitleTableViewCell *cell =(RestaurantMenuTitleTableViewCell*) [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[RestaurantMenuTitleTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"RestaurantMenuTitleTableViewCell" owner:self options:nil];
cell = [topLevelObjects objectAtIndex:0];
}
RestaurantMenuItemObject *object = [self.restauRantMenuArray objectAtIndex:indexPath.section];
cell.titleWebView.opaque = NO;
cell.titleWebView.backgroundColor = [UIColor clearColor];
[cell.titleWebView loadHTMLString:object.menuTitle baseURL:nil];
cell.titleWebView.scrollView.scrollEnabled = NO;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.backgroundColor = [UIColor whiteColor];
return cell;
}
else
{
static NSString *MyIdentifier = #"menuContentCell";
RestaurantMenuContentTableViewCell *cell =(RestaurantMenuContentTableViewCell*) [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[RestaurantMenuContentTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"RestaurantMenuContentTableViewCell" owner:self options:nil];
cell = [topLevelObjects objectAtIndex:0];
}
RestaurantMenuItemObject *object = [self.restauRantMenuArray objectAtIndex:indexPath.section];
cell.contentWebView.tag = indexPath.section + 1000;
cell.contentWebView.opaque = NO;
cell.contentWebView.backgroundColor = [UIColor clearColor];
[cell.contentWebView loadHTMLString:object.menuContent baseURL:nil];
//cell.contentWebView.scrollView.delegate = self;
[cell.contentWebView.scrollView setShowsHorizontalScrollIndicator:NO];
// cell.contentWebView.scrollView.scrollEnabled = NO;
//cell.contentWebView.delegate = self;
if([[self.imageHeightArray objectAtIndex:indexPath.section] isEqualToString:#"150"])
{
//cell.contentWebView.delegate = self;
}
// first row
//cell.textLabel.text = #"Expandable"; // only top row showing
if ([expandedSections containsIndex:indexPath.section])
{
//cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeUp];
}
else
{
//cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeDown]
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.backgroundColor = [UIColor clearColor];
return cell;
}
}
else
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.backgroundColor = [UIColor clearColor];
return cell;
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
RestaurantMenuItemObject *object = [self.restauRantMenuArray objectAtIndex:indexPath.section];
UIWebView *thisWebView = (UIWebView*)[self.restaurantMenuTableView viewWithTag:indexPath.section+1000];
[thisWebView loadHTMLString:object.menuContent baseURL:nil];
thisWebView.delegate = self;
//[tableView deselectRowAtIndexPath:indexPath animated:YES];
//if there is any previous selected index
//if selected index is not the previous selected
if (selectedIndex && (selectedIndex.section != indexPath.section)) {
[self collapseOrExpandForIndexPath:selectedIndex inTableView:tableView];
}
if ([selectedIndex isEqual:indexPath]) {
selectedIndex = nil;
}
else{
selectedIndex = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
}
if ([self tableView:tableView canCollapseSection:indexPath.section])
{
[self collapseOrExpandForIndexPath:indexPath inTableView:tableView];
if (indexPath.row == 0) {
[tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
}
}
- (void)collapseOrExpandForIndexPath:(NSIndexPath *)indexPath inTableView:(UITableView *)tableView{
if (!indexPath.row)
{
// only first row toggles exapand/collapse
//[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSInteger section = indexPath.section;
BOOL currentlyExpanded = [expandedSections containsIndex:section];
NSInteger rows;
NSMutableArray *tmpArray = [NSMutableArray array];
if (currentlyExpanded)
{
rows = [self tableView:tableView numberOfRowsInSection:section];
[expandedSections removeIndex:section];
}
else
{
[expandedSections addIndex:section];
rows = [self tableView:tableView numberOfRowsInSection:section];
}
for (int i=1; i<rows; i++)
{
NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i
inSection:section];
[tmpArray addObject:tmpIndexPath];
}
if (currentlyExpanded)
{
[tableView deleteRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
}
else
{
//RestaurantMenuItemObject *object = [self.restauRantMenuArray objectAtIndex:indexPath.section];
// UIWebView *thisWebView = (UIWebView*)[self.restaurantMenuTableView viewWithTag:indexPath.section+1000];
//
// [thisWebView loadHTMLString:object.menuContent baseURL:nil];
//
// thisWebView.delegate = self;
[tableView insertRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
}
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//return UITableViewAutomaticDimension;
if(indexPath.row == 0)
return 50.00;
else
{
return 240;//[[self.imageHeightArray objectAtIndex:indexPath.section] integerValue];
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 1.00;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return 1.00;
}
pragma mark Table View Delegate Method ends
Create a class level property (CGFloat),say webViewHeight to track web view's height.
On table view didSelectRowAtIndexPath method load url in web view.
Calculate web view height in webviewDidFinishLoad delegate method of web view and set it in class level height variable,webViewHeight. After calculating height call [tableView reloadData];
Set selected cell height with webViewHeight and rest with default,say 44.0 in heightForRowAtIndexPath method of data source.
IMP: Set maximum web view height also if calculated height exceed max height set calculated height to max height. And enable web view scrolling so that user is able to view all web view content.
I am working with the tableview and working well with that. But i stuck at one place where i want to tap the cell and on the tap the cell should expand its height and and the cell below it should move down according to the expanded height.
The code which i am using is as follows.
- (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];
}
[cell.textLabel setNumberOfLines:0]; // unlimited number of lines
gratitude *grat = [gratitude_list objectAtIndex:indexPath.row];
cell.textLabel.text=grat.gratitude;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
[cell.textLabel setFont:[UIFont fontWithName:#"Lucida Sans" size:20]];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
gratindex > -1;
if (gratindex == indexPath.row) {
[self collapseSubItemsAtIndex:indexPath];
gratindex = -1;
}
else {
BOOL shouldCollapse = gratindex > -1;
if (shouldCollapse) {
[self collapseSubItemsAtIndex:gratindex];
}
gratindex = (shouldCollapse && indexPath.row > gratindex) ? indexPath.row - [[gratitude_list objectAtIndex:gratitude_list] count] : indexPath.row;
[self expandItemAtIndex:gratitude_list];
}
[self.gratitude_tableview endUpdates];
}
- (void)expandItemAtIndex:(int)index
{
NSMutableArray *indexPaths = [NSMutableArray new];
int insertPos = index + 1;
for (int i = 0; i < [gratitude_list count]; i++) {
[indexPaths addObject:[NSIndexPath indexPathForRow:insertPos++ inSection:0]];
}
[self.gratitude_tableview insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
[self.gratitude_tableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
- (void)collapseSubItemsAtIndex:(int)index {
NSMutableArray *indexPaths = [NSMutableArray new];
for (int i = index + 1; i <= index + [[gratitude_list objectAtIndex:index] count]; i++) {
[indexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];
}
[self.gratitude_tableview deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
}
Please help me out if i am using wrong approch please help me out.
Please check my answer. If you need any more detailing then you can ask me in comment.
UPDATED:
ANd in .h file
#interface tableViewDemoViewController : UITableViewController
{
NSIndexPath *selectedCellIndexPath;
BOOL clickedAgain;
int heights;
}
And in .m file
#import "tableViewDemoViewController.h"
#interface tableViewDemoViewController ()
#end
#implementation tableViewDemoViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
clickedAgain = YES;
heights =0;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
// Return the number of rows in the section.
return 15;
}
- (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];
}
// Configure the cell...
cell.textLabel.text = [NSString stringWithFormat:#"This is cell %d",indexPath.row ];
return cell;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:NO];
if ([selectedCellIndexPath compare:indexPath] == NSOrderedSame && !clickedAgain)
{
heights =40;
clickedAgain =YES;
}
else
{
heights =80;
clickedAgain = NO;
}
[tableView beginUpdates];
selectedCellIndexPath = indexPath;
[tableView endUpdates];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if(selectedCellIndexPath != nil
&& [selectedCellIndexPath compare:indexPath] == NSOrderedSame )
{
return heights;
}
return 40;
} #end
I am working with the table view. I added the checkmark Accessory on the first tap of the screen and removed this checkmark on the second tap. I added few ckeckmarks on the cells of table view. Now i want that the labels of the cells having the checkmarks should be displayed on the NSlog.
please help me out regarding this issue. Any help will be much appriciable.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView.tag == 0)
{
return [celltitles count];
}
else
{
return 7;
}
}
- (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];
}
if (tableView.tag == 0)
{
cell.textLabel.text = [celltitles objectAtIndex:indexPath.row];
if (indexPath.row == 0)
{
habitname = [[UITextField alloc]initWithFrame:CGRectMake(150, 0, 150, 50)];
habitname.placeholder = #"Habit Name";
habitname.delegate= self;
[cell addSubview:habitname];
}
else if (indexPath.row == 1)
{
timelbl = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 220, 50)];
timelbl.text = #"OFF";
timelbl.textAlignment = NSTextAlignmentCenter;
[cell addSubview:timelbl];
timetitlelbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 50)];
timetitlelbl.text = #"Alert";
timetitlelbl.textAlignment = NSTextAlignmentCenter;
[cell addSubview:timetitlelbl];
toggleswitch = [[UISwitch alloc] initWithFrame:CGRectMake(250, 5, 50, 60)];
toggleswitch.on = NO;
[toggleswitch addTarget:self action:#selector(toggleSwitch) forControlEvents:(UIControlEventValueChanged | UIControlEventTouchDragInside)];
[cell addSubview:toggleswitch];
}
}
else if (tableView.tag == 1)
{
cell.textLabel.text = [daysarray objectAtIndex:indexPath.row];
}
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 1)
{
if (toggleswitch.on)
{
[self datepickershown:timelbl.text animated:YES];
if (self.datePickerIsShowing)
{
//[self datepickershown];
//[self hideDatePickerCell];
[dscptxt resignFirstResponder];
}
else
{
[dscptxt resignFirstResponder];
[self.timelbl resignFirstResponder];
[self showDatePickerCell];
}
}
else
{
timelbl.textColor = [UIColor grayColor];
}
}
else if (indexPath.row > 2 && indexPath.row <10)
{
NSLog(#"I am Selectin the row");
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryNone)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else if (cell.accessoryType == UITableViewCellAccessoryCheckmark)
{
// NSLog(#"Selected Accessory Is %d",cell.accessoryType);
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
[self.tableview deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)savedata:(id)sender
{
}
Above is the code which i am using and on the save action i want the log.
Don't use the UITableView to store your data. Cells are reused, so that's not a reliable way to detect which items you have selected.
You could store whether an item is selected in an array, for instance. Then in your cellForRowAtIndexPath determine if the checkmark should be displayed. In didSelectRowAtIndexPath you update the model (your array) and request a reload for the specific cell.
This will result in a better MVC separation.
EDIT: added example for the UITableView stuff
// for this example we'll be storing NSIndexPath objects in our Model
// you might want to use a #property for this
NSMutableSet *model = [NSMutableSet set];
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
...
if([model containsObject:indexPath]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
...
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
...
// update the model
if([model containsObject:indexPath]) {
[model removeObject:indexPath];
}
else {
[model addObject:indexPath];
}
// request reload of selected cell
[tableView reloadRowsAtIndexPaths:#[indexPath] withRowAnimation: UITableViewRowAnimationFade];
...
}
Now it should be fairly easy to log all selected items, without having to use the UITableView: it's all in your model now!
Make a for loop:
NSMutableArray *mutArray = [[NSMutableArray alloc] init];
for(i = 0;i <= self.rowCount-1;i++)
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
if (cell.accessoryType == UITableViewCellAccessoryCheckmark)
{
[mutArray addObject:[NSIndexPath indexPathForRow:i inSection:0]];
}
}
NSLog(#"Array: %#", mutArray);