Collapse / Expand a specific cell in UITableView - ios

I currently have 2 categories (cat, dog) in 1 UITableView.
This is the illustration:
The cat and dog button are part of the UITableView they are in the header section.
they act as a separator for both categories.
what i'm trying to achieve is when i click the cat button, the list under the cat button should collapse and the dog button should re - adjust it's position.
When i click again the cat button, the list should expand.
what i currently have is :
NSUInteger indexes = (unsigned long)filteredList.count;
for (int i = 0 ; i <= indexes - 1 ; i++)
{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
[self.accountBalanceTableView cellForRowAtIndexPath:indexPath].hidden = YES;
}
It hides all of my cat list but the dog button is not adjusting it's position where it just leaves a huge amount of white space in the screen.

There are two possibilities you can do this.
Change the height of the rows in the section you want to hide.
Return 0 for the rows in the section you want to hide.

you can use two cell(maincell,subcell)in your table and put this code in cell for row at indexpath.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (tableView == _tblDispChapters) {
if(indexPath.row == 0){
TVCDispChapters *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
//Accuracy
int acu;
if ([[marrParentChapters objectAtIndex:indexPath.section]valueForKey:#"acuracy"]==[NSNull null] ) {
NSLog(#"%#",[[marrParentChapters objectAtIndex:indexPath.section]valueForKey:#"acuracy"]);
acu=0;
}
else
{
acu=[[[marrParentChapters objectAtIndex:indexPath.section]valueForKey:#"acuracy"] intValue];
NSLog(#"%d",acu);
}
cell.lbl_acu.text=[NSString stringWithFormat:#"Accuracy %d%%",acu];
[cell.pro_cell_chapt.layer setCornerRadius:cell.pro_cell_chapt.frame.size.height/2];
cell.pro_cell_chapt.clipsToBounds = true;
[cell.pro_cell_chapt setTransform:CGAffineTransformMakeScale(1.0f, 2.0f)];
cell.pro_cell_chapt.progress = acu/100.0;
cell.pro_cell_chapt.trackTintColor = [UIColor colorWithHex:0xDDDDDD];
cell.pro_cell_chapt.progressTintColor = [UIColor colorWithHex:0xEF9430];
cell.lblChepterName.text = [[marrParentChapters objectAtIndex:indexPath.section]valueForKey:#"ChapterName"];
[cell.btn_sel_allchptr setTag:indexPath.section];
[cell.btn_sel_allchptr addTarget:self action:#selector(checkBoxClicked:)forControlEvents:UIControlEventTouchUpInside];
if ([[_marrHideShowSection objectAtIndex:indexPath.section] boolValue]){
[cell.imgArrow setImage:[UIImage imageNamed:#"up-arrow1"]];
}else{
[cell.imgArrow setImage:[UIImage imageNamed:#"down-arrow1"]];
}
if ([[_marrAllChapter objectAtIndex:indexPath.section] boolValue]){
[cell.img_cpt_select setImage:[UIImage imageNamed:#"checkbox-selected1"]];
}else{
[cell.img_cpt_select setImage:[UIImage imageNamed:#"checkbox-unselected1"]];
}
return cell;
}else{
TVCDispChapters *cell = [tableView dequeueReusableCellWithIdentifier:#"sub_Cell" forIndexPath:indexPath];
cell.lblSubChapterName.text = [[[marrSubChapters objectAtIndex:indexPath.section] objectAtIndex:indexPath.row-1]valueForKey:#"ChapterName"];
if ([[[_marrSelectionSection objectAtIndex:indexPath.section] objectAtIndex:indexPath.row-1] boolValue])
{
[cell.imgSelection setImage:[UIImage imageNamed:#"checkbox-selected1"]];
}else{
[cell.imgSelection setImage:[UIImage imageNamed:#"checkbox-unselected1"]];
}
return cell;
}
}else{
QuestionTypeTVC *cell1 = [tableView dequeueReusableCellWithIdentifier:#"CellQuesType" forIndexPath:indexPath];
if ([_marrSelectedQuestionypeID containsObject:[[_marrQuestiontype objectAtIndex:indexPath.row] valueForKey:#"QuestionTypeID"]]){
cell1.imgSelection.image = [UIImage imageNamed:#"checkbox-selected1"];
}else{
cell1.imgSelection.image = [UIImage imageNamed:#"checkbox-unselected1"];
}
cell1.lblQuesType.text=#"1";
return cell1;
}
}

Related

Change background color for a particular index cell in iOS

I have a table with number of cells, with each cell having one UIButton. When I click on that button the button cell background color should change. Here is my partial code for your understanding.
When I click on this button all my tableview cells background colors are getting changed. How to do it only for the selected cell?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = #"SimpleTableCell";
cell = (MenuCell *)[menuTableview dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"MenuViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
[cell initState];
// Listens for method calls on cell
cell.delegate = self;
}
if ((self.TempArray.count != 0)) {
for (int i=0; i<TempArray.count; i++) {
if ([self.TableviewArray objectAtIndex:indexPath.row] == TempArray[i]) {
if (cell.backgroundColor != [UIColor lightGrayColor]) {
cell.backgroundColor = [UIColor lightGrayColor];
}
UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
button.tag=indexPath.row;
[button addTarget:self action:#selector(aMethod:) forControlEvents:UIControlEventTouchDown];
[button setTitle:#"UnHide" forState:UIControlStateNormal];
button.frame = CGRectMake(200.0, 20.0, 160.0, 40.0);
[cell.contentView addSubview:button];
}
}
}
// Set index for this cell (it could be wrong if cell is re-used)
cell.downloadIndex = (int)indexPath.row;
Download *download = [TableviewArray objectAtIndex:indexPath.row];
cell.downloading = download.downloading;
cell.completed = download.completed;
cell.MenuLang.text = download.name;
cell.downLoadPrgView.progress = download.percentageDownloaded;
// Check for completed status
cell.completed = download.completed;
cell.CompletedMenuLang.text = download.name;
return cell;
}
-(void)aMethod:(UIButton*)sender {
NSLog(#"I Clicked a button %d",sender.tag);
int row = sender.tag;
}
Just implement below code, you can change background colour of particular cell as well as hide the selected button.
-(void)aMethod:(UIButton*)sender {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag inSection:0];
Friends1TableViewCell *cell = (Friends1TableViewCell *)[self.tblVW cellForRowAtIndexPath:indexPath];
cell.backgroundColor = [UIColor redColor];
sender.hidden = YES;
}
-(IBAction)BTNTapped:(UIButton *)sender
{
CGPoint buttonPosition = [sender convertPoint:CGPointZero
toView: menuTableview];
NSIndexPath *tappedIP = [menuTableview indexPathForRowAtPoint:buttonPosition];
}
do change using this indexpath of cell
Here is my answer..
-(void)aMethod:(UIButton*)sender
{
NSLog(#"I Clicked a button %d",sender.tag);
int row = sender.tag;
NSIndexPath *path = [NSIndexPath indexPathForRow:row inSection:0];
UITableViewCell *cell = [menuTableview cellForRowAtIndexPath:path];
cell.contentView.backgroundColor = [UIColor whiteColor];
}
try this
#property (nonatomic, assign) NSInteger selectedRow;
self.selectedRow = -1; // init with -1
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// ...
if(self.selectedRow == indexPath.row) {
cell.backgroundColor = SELECTED_COLOR;
}
else {
cell.backgroundColor = NORMAL_COLOR;
}
return cell;
}
-(void)aMethod:(UIButton*)sender {
// ...
self.selectedRow = row;
[self.myTableView reloadData];
}

Keep selected state of UITableViewCells when scrolling

I am trying to keep the selected state of multiple cells on a didSelectRowAtIndexPath method. I have an edit button that I've set up that loops through every cell to select each field on my UITableView.
Here is the code for the edit button on tap that selects all my rows.
- (IBAction)editButtonTapped:(id)sender {
for (int i = 0; i < self.caseDataTableView.numberOfSections; i++) {
for (NSInteger r = 0; r < [self.caseDataTableView numberOfRowsInSection:i]; r++) {
[self tableView:caseDataTableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:r inSection:i]];
}
}
}
When calling the didSelectRowAtIndexPath method, it does the following code.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
OKOperatieNoteTableViewCell *cell = (OKOperatieNoteTableViewCell *)[self.caseDataTableView cellForRowAtIndexPath:indexPath];
cell.cellIndexPath = indexPath;
[cell hideLabelAndShowButtons];}
Incase you were wondering here is the hideLabelAndShowButtons method.
- (void)hideLabelAndShowButtons {
self.caseDataKeyLabel.hidden = NO;
if (!self.disabled) {
self.caseDataValueLabel.hidden = YES;
self.textField.hidden = NO;
if ([self.inputType isEqualToString:#"switcher"] || [self.inputType isEqualToString:#"multiselect"] || [self.inputType isEqualToString:#"picker"] || [self.inputType isEqualToString:#"DatePicker"] || [self.inputType isEqualToString:#"selectContact"]) {
self.button.hidden = NO;
}else {
self.button.hidden = YES;
}
}
self.caseDataDescriptionTextView.hidden = YES;}
Now at this point, I have all my rows selected. If I scroll down and then back up the selection of these rows is not there anymore. Now I'm aware when you go in and out of the view, the cellForRowAtIndexPath method recreates these cells. The following is my cellForRowAtIndexPath method.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"caseData";
OKOperatieNoteTableViewCell * cell = [[OKOperatieNoteTableViewCell alloc]init];
cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (indexPath.row < _procedureVariables.count) {
if ([[[_caseDataArray objectAtIndex:indexPath.row] valueForKey:#"key"] isEqualToString:#"Procedure"]) {
[cell setLabelsWithKey:[[_caseDataArray objectAtIndex:indexPath.row] valueForKey:#"key"] AndValue:[self.model valueForKey:#"var_procedureName"]];
}else {
[cell setLabelsWithKey:[[_caseDataArray objectAtIndex:indexPath.row] valueForKey:#"key"] AndValue:[[_caseDataArray objectAtIndex:indexPath.row] valueForKey:#"value"]];
}
OKProcedureTemplateVariablesModel *variableModel = _procedureVariables[indexPath.row];
cell.variable = variableModel.value;
[cell showLabelAndHideButtons];
cell.delegate = self;
[cell setUpCellType];
} else if (indexPath.row == _procedureVariables.count) {
NSString *text = [NSString stringWithFormat:#"%# \n\n %#", [_templateDictionary objectForKey:#"indicationText"], [_templateDictionary objectForKey:#"procedureText"] ];
[cell showDescription:text];
NSLog(#"cell.caseDataDescriptionTextView.font.fontName = %#", cell.caseDataDescriptionTextView.font.fontName);
}
cell.procedureID = _procedureID;
[tableView setContentInset:UIEdgeInsetsMake(1.0, 0.0, 0.0, 0.0)];
return cell;
}
I'm just trying to figure out how to keep the selected state of these cells once the cellForRowAtIndexPath method is called. Any suggestions are welcomed.
i tried to simulate your situation, created a customCell and saved the indexpaths of selectedRows in my custom selectedPaths mutable array(initialized in viewDidLoad).
After every click i removed or added related indexpath to my array.
it worked for my case. Hope it helps.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"caseData";
NOTableViewCell *cell = (NOTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
NSLog(#"new cell created for row %d", (int)indexPath.row);
cell = [[[NSBundle mainBundle] loadNibNamed:#"NOTableViewCell" owner:self options:nil] objectAtIndex:0];
}
if ([selectedPaths indexOfObject:indexPath] != NSNotFound) // this cell is in selected state.
{
[cell.textLabel setText:#"This cell selected"];//selected state job.
return cell;
}
[cell.textLabel setText:[NSString stringWithFormat:#"%d", (int)indexPath.row]];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([selectedPaths indexOfObject:indexPath] != NSNotFound) {
[selectedPaths removeObject:indexPath];
}
else{
[selectedPaths addObject:indexPath];
}
//[tableView reloadData];
[tableView reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationNone];//instead of reloading all just reload clicked cell.
}
You need to update the cell to selected and not selected explicitly in both directions in cellForRowAtIndexPath.
If not, the recycled cells will just show the value of the cell the cell was last used for until you change it.
While you are invoking the delegate method in order to call hideLabelAndShowButtons, you aren't telling the table view that you have selected the row;
- (IBAction)editButtonTapped:(id)sender {
for (int i = 0; i < self.caseDataTableView.numberOfSections; i++) {
for (NSInteger r = 0; r < [self.caseDataTableView numberOfRowsInSection:i]; r++) {
NSIndexPath *path=[NSIndexPath indexPathForRow:r inSection:i];
[caseDataTableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
[self tableView:caseDataTableView didSelectRowAtIndexPath:path];
}
}
}
Also, you aren't using the cell selection state in cellForRowAtIndexPath, so you probably need to change some code there too, but I am not sure what the relationship is between selected state and how you want to render the cell.

UITableView add more cells with Click

I added UIButton in the last cell of UITableView, and I want to show more cells with click..
- (void)viewDidLoad {
[super viewDidLoad];
rowCount = 15;
dataArray = [[NSMutableArray alloc] init];
for (int i = 0; i < 100; i++) {
NSString *value = [NSString stringWithFormat:#"the value of row is: %d", i +1];
[dataArray addObject:value];
}
}
...
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return rowCount;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *idintify = #"Cell";
UITableViewCell *cell = [self.myTable dequeueReusableCellWithIdentifier:idintify];
[cell.textLabel setText:dataArray[indexPath.row]];
if (indexPath.row == rowCount -1) {
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, self.myTable.frame.size.width, 44)];
[button addTarget:self action:#selector(cellButtonClicked) forControlEvents:UIControlEventTouchUpInside];
[button setBackgroundColor:[UIColor yellowColor]];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button setTitle:#"Show more..." forState:UIControlStateNormal];
[cell addSubview:button];
}
return cell;
}
...
- (void)cellButtonClicked
{
if (rowCount +10 >= dataArray.count) {
rowCount = dataArray.count;
} else {
rowCount += 10;
}
[self.myTable reloadData];
NSLog(#"%ld", (long)rowCount);
}
At beginning its work properly, But when I scrolled the table the cell did not changed!
I want to show the button at last cell
Cells in a table view are reused when the user scrolls. When you add a button to an instance of your cell prototype and don't remove it, the button remains, even if the cell is used at another index later. This results in what you have on your screenshots.
You should create two cell prototypes in the interface builder and your cellForRow:atIndexPath: should look something like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return cell with data
if (indexPath.row < dataArray.count) {
UITableViewCell *cell = [self.myTable dequeueReusableCellWithIdentifier:#"cell_prototype_1"];
[cell.textLabel setText:dataArray[indexPath.row]];
return cell;
}
// If it's the last index, return cell with button
else {
UITableViewCell *cell = [self.myTable dequeueReusableCellWithIdentifier:#"cell_prototype_2"];
return cell;
}
// This won't get called
return [UITableViewCell new];
}
That will be better if you use two different cells otherwise replace the code in your cellForRowAtIndexPath
if (indexPath.row == rowCount -1){}
with
if ( (indexPath.row-15)%10 == 0 ){}
and Put
[cell.textLabel setText:dataArray[indexPath.row]];
in the else part.
and place code just below UITableViewCell *cell....
for(UIView *view in cell.view.subviews){
if([view isKindOfClass: [UIButton class]]){
[view removeFromSuperView];
}
}
I think you need to refresh visible cells, doing:
[tableView reloadRowsAtIndexPaths:[tableView indexPathsForVisibleRows]
withRowAnimation:UITableViewRowAnimationNone];
Also better way to do it would be that you have 2 prototype cells, one for data, one with button. let's sey you give the second one identifier "buttonCell", than you just do this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *idintify = (indexPath.row < rowCount -) ? #"Cell" : #"buttonCell";
UITableViewCell *cell = [self.myTable dequeueReusableCellWithIdentifier:idintify];
if (cell == nil) //initialize
if (indexPath.row < rowCount -1) {
[cell.textLabel setText:dataArray[indexPath.row]];
}
return cell;
}
and in didSelectRowAtIndexPath you increase rowCount and reload data if indexPath.row == rowCount - 1

how to stop the display button click (change button image) in other cell (clicked cell image is changed ) when uitableview scroll?

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1; //count of section
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 30; //count number of row from counting array hear cataGorry is An Array
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *testword=#"pass";
if ([testword isEqualToString:#"pass"]) {
static NSString *MyIdentifier = #"cell1";
TextTableViewCell *cell ;
cell= [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
cell.lblText.text=[NSString stringWithFormat:#"textcelll= %i", indexPath.row+1];
cell.btnTextbox.tag=indexPath.row;
[cell.btnTextbox addTarget:self action:#selector(customActionPressed:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}else{
static NSString *MyIdentifier1 = #"cell2";
ImageTableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:MyIdentifier1];
return cell1;
}
}
-(void)customActionPressed:(UIButton*)sender{
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView1];
NSIndexPath *indexPath = [self.tableView1 indexPathForRowAtPoint:buttonPosition];
TextTableViewCell *cell = (TextTableViewCell*)[self.tableView1 cellForRowAtIndexPath:indexPath];
if (indexPath != nil)
{
int currentIndex = indexPath.row;
NSLog(#"currentIndex == %d",currentIndex);
int tableSection = indexPath.section;
NSLog(#"tableSection == %d",tableSection);
}
if (!cell.btnTextbox.isSelected ){
cell.btnTextbox.selected=YES;
[cell.btnTextbox setImage:[UIImage imageNamed:#"checkClick.png"] forState:UIControlStateNormal];
NSLog(#"button tag %i",cell.btnTextbox.tag);
NSLog(#"check click");
}else{
cell.btnTextbox.selected=NO;
[cell.btnTextbox setImage:[UIImage imageNamed:#"check.png"] forState:UIControlStateNormal];
NSLog(#"check ");
}
in simulator , when i am clicked the button in first row (indexpath.row=0) then i am scrolling tableview, button click will auto display in 7th row (indexpath.row=6)
Question is ,i want to know , what happened in really and how to avoid this (when i'm scrolling)?
Since cells are being reused, you have to (in your cellForRowAtIndexPath) to set image to one state or another (to set one image or another).
What really happen is that you set Image for one cell but that cell is being reused through whole table. You use only 5(lets say that is how much you cells can fit into one screen) cells and when you load next you actually reuse the one with an image.
So, in your cellForRowAtIndexPath you will have to check if the button state is selected or not and then assign appropriate image.
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *testword=#"pass";
if ([testword isEqualToString:#"pass"]) {
static NSString *MyIdentifier = #"cell1";
TextTableViewCell *cell ;
cell= [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
cell.lblText.text=[NSString stringWithFormat:#"textcelll= %i", indexPath.row+1];
cell.btnTextbox.tag=indexPath.row;
if (cell.btnTextbox.isSelected ){
[cell.btnTextbox setImage:[UIImage imageNamed:#"checkClick.png"] forState:UIControlStateNormal];
}else{
[cell.btnTextbox setImage:[UIImage imageNamed:#"check.png"] forState:UIControlStateNormal];
}
[cell.btnTextbox addTarget:self action:#selector(customActionPressed:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}else{
static NSString *MyIdentifier1 = #"cell2";
ImageTableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:MyIdentifier1];
return cell1;
}
}
For completness sake, I would also suggest you to use Accessory type as well as Xib files for these kind of cells. You can set it in storyboard under accessory dropdown or through code:
cell.accessoryType = UITableViewCellAccessoryCheckmark;

How can I send the relevant UITextField text data to the function in a collapsable UITableView?

I have this collapsable UITableView where there is a UITextField and a UIButton in the last cell in each table section. I would like to send the text in the UITextField to the function that is called by the UIButton that is next to it in the same cell, but I am baffled in how to achieve this. Thanks in advance for the help!
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:nil];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if ([self tableView:_tableView canCollapseSection:indexPath.section])
{
int num = 1;
if (self.chat[indexPath.section - 1][#"num"] != nil)
num = [self.chat[indexPath.section - 1][#"num"] intValue] + 1;
if (!indexPath.row)
{
cell.textLabel.text = self.chat[indexPath.section - 1][#"msg"]; // 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];
}
}
else if (indexPath.row < num && indexPath.row >= 1)
{
cell.textLabel.text = self.chat[indexPath.section - 1][key];
cell.accessoryView = nil;
}
else
{
///////////////////////////////////////////
////////This is the important part/////////
///////////////////////////////////////////
UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(14, 6, 245, 31)];
self.sendButton = [[UIButton alloc] initWithFrame:CGRectMake(265, 1, 50, 40)];
[self.sendButton setTitle:#"Reply" forState:UIControlStateNormal];
[self.sendButton setTitleColor:UIColorFromRGB(0x960f00) forState:UIControlStateNormal];
[cell addSubview:self.sendButton];
[self.sendButton addTarget:self action:#selector(sendReply:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:field];
cell.accessoryView = nil;
}
}
else
{
cell.accessoryView = nil;
cell.textLabel.text = #"Normal Cell";
}
return cell;
}
Give some unique tag to textfield and button by below way:
///////////////////////////////////////////
////////This is the important part/////////
///////////////////////////////////////////
UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(14, 6, 245, 31)];
self.sendButton = [[UIButton alloc] initWithFrame:CGRectMake(265, 1, 50, 40)];
[self.sendButton setTitle:#"Reply" forState:UIControlStateNormal];
[self.sendButton setTitleColor:UIColorFromRGB(0x960f00) forState:UIControlStateNormal];
self.sendButton.tag = indexPath.section *1000 + indexPath.row;
[cell addSubview:self.sendButton];
[self.sendButton addTarget:self action:#selector(sendReply:) forControlEvents:UIControlEventTouchUpInside];
field.tag = self.sendButton.tag + 1;
[cell addSubview:field];
cell.accessoryView = nil;
Now on button event,
-(void) sendReply:(UIButton *)sender
{
UITextField *field = [YOOUR_TABLE_VIEW viewWithTag:sender.tag + 1];
//Do you coding here
}
Make a Custom UITableViewCell that has uitextfield and a button on it and make a protocol/delegate of that custom uitableviewcell you've created.. so you can have more control of your code and the event of your button in the future..
check this tutorial: http://www.codigator.com/tutorials/ios-uitableview-tutorial-custom-cell-and-delegates/
cheers
For this,
In cellForRowAtIndexPath: method where you are allocating the send button add one line just to give some identifier to send button as below,
[self.sendButton setAccessibilityIdentifier:[NSString stringWithFormat:#"%d#%d",indexPath.row,indexPath.section]];
Now, in sendReply: method,
//First get the row and section information
NSString *str=[sender accessibilityIdentifier];
NSArray *arr=[str componentsSeparatedByString:#"#"];
//Get the index path
NSIndexPath *iRowId =[NSIndexPath indexPathForRow:[[arr objectAtIndex:0] intValue] inSection:[arr objectAtIndex:1] intValue]];
//get the cell
UITableViewCell *objCell=(UITableViewCell*)[tblviwBasketCell cellForRowAtIndexPath:iRowId];
Now objCell will be the cell in which you have added the button and text view. so get the subviews of objCell and access the textfield to get the text.
As you say, there is a text field in each section. You should set the tag of your UIButton and UITextField same as indexPath.section.
Then, in the target method, use this tag value to get the relevant cell from the relevant section, and iterate over it's subviews to get your textField.
In the target method, you should do something like this:
- (void) sendReply:(id)sender {
int section = [(UIButton*)sender tag];
int row = [myTableView numberOfRowsInSection:section] - 1;//assuming it is the last cell in the section that contains your textField.
NSIndexPath* indexPath = [NSIndexPath indexPathForRow:row inSection:section];
UITableViewCell* cell = [myTableView cellForRowAtIndexPath:indexPath];
for (UIView* vu in cell.subviews) {
if ([vu isKindOfClass:[UITextField class]]) {
NSString* textString = [(UITextField*)vu text];
//perform any tasks you want with the text now
}
}
}
You can simply use viewWithTag:, since it does an iterative search, but all the extra code is to avoid iterating over all the cells before reaching your relevant cell.

Resources