I am facing issue regarding Dynamic cell in UITableView. I want to create dynamic rows while user clicked on button in tableview.
E.g.: in mytableview there are two rows as following :
Car :+
Bike :+
When user clicked add button then I have to show two more rows below car cell same thing as while user clicked on in front of bike add button then I have to show two more cells.
I think you need to have 2 sections, a bike and a car section with two data arrays to manage content of all cells. You may need to have two types of cell, an "add" cell and a "standard" cell.
Here is an example:
-In your viewDidiLoad:
self.bikeArray = [NSMutableArray arrayWithArray:#[#"Add bike"]]; // Aray to fill section 0
self.carArray = [NSMutableArray arrayWithArray:#[#"Add car"]]; // Aray to fill section 1
self.typeOfVehicleArray = #[#"Bike", #"Car"];
self.dataArray = #[self.bikeArray, self.carArray];
To create two types of cell, check indexPath.row:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell;
switch (indexPath.row) {
case 0:{
NSString *addIdentifier = #"addIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:addIdentifier];
if (!cell){
// Add button...
CGFloat buttonWidth = 60.f;
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:addIdentifier];
UIButton *b = [[UIButton alloc] initWithFrame:CGRectMake(cell.frame.size.width - buttonWidth - 10.f , 5.f, buttonWidth, cell.frame.size.height - 10.f)];
[b setTitle:#"ADD" forState:UIControlStateNormal];
// ...with a wonderful color
b.backgroundColor = [UIColor greenColor];
[b addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:b];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
break;
}
default:{
NSString *standardIdentifier = #"standardIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:standardIdentifier];
if (!cell){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:standardIdentifier];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
break;
}
}
NSArray *vehicleArray = self.dataArray[indexPath.section];
cell.textLabel.text = [vehicleArray objectAtIndex:indexPath.row];
return cell;
}
Don't forget number of cells / sections:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [self.dataArray count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSArray *vehicleArray = self.dataArray[section];
return [vehicleArray count];
}
Then you can implement buttonPressed:
- (void) buttonPressed: (id)sender{
// Find the section
UIButton *b = (UIButton *)sender;
UITableViewCell *cell = (UITableViewCell *)[b superview];
NSInteger section = [self.tableView indexPathForCell:cell].section;
// Get vehicle array (bikeArray or carArray)
NSMutableArray *vehicleArray = self.dataArray[section];
NSString *vehicleType = [self.typeOfVehicleArray objectAtIndex:section];
NSInteger nextVehicle = [vehicleArray count];
NSString *firstRowToAdd = [NSString stringWithFormat:#"%# %lu", vehicleType, (long)nextVehicle];
NSString *secondRowToAdd = [NSString stringWithFormat:#"%# %lu", vehicleType, (long)(nextVehicle + 1)];
// Add object in vehicle array
[vehicleArray addObject:firstRowToAdd];
[vehicleArray addObject:secondRowToAdd];
// Create array of corresponding indexPath and update tableview
NSArray *indexPathArray = #[[NSIndexPath indexPathForRow:nextVehicle inSection:section],
[NSIndexPath indexPathForRow:(nextVehicle + 1) inSection:section]];
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationRight];
[self.tableView endUpdates];
}
You can control number rows in UITableView's tableView:numberOfRowsInSection: function that is defined in UITableViewDataSource Protocol. Just define an integer variable that holds the number rows user should see. On every Add button click increase the value of variable.
#implementation ViewController {
int numberOfRows;
}
- (void)viewDidLoad {
[super viewDidLoad];
numberOfRows = 3;
}
-(IBAction) addButtonClicked
{
numberOfRows++;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return numberOfRows;
}
Related
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];
}
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.
Trying to implement the checkmark for UITableView.
Checkmark for UITableView Cell is not selecting to all row, when scroll tableview
its not not enable.
Below is my code which i Implemented.
IndexButton is UIButton Class which added index init.
-(void)selectAllAction:(IndexedButton *)sender{
for (int rowIndex = 0; rowIndex < [array_MedicineList count]; rowIndex++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:rowIndex inSection:0];
UITableViewCell *cell = [tbl_ProductList cellForRowAtIndexPath:indexPath];
IndexedButton *btn_SelectItem = (IndexedButton *)[cell viewWithTag:TAG_SELECTEDITEM];
[btn_SelectItem setBackgroundImage:[UIImage imageNamed:#"checkMark"] forState:UIControlStateNormal];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *productListTableViewCell = #"ProductListTableViewCell";
ProductListTableViewCell *cell = (ProductListTableViewCell *)[tableView dequeueReusableCellWithIdentifier:productListTableViewCell];
if (cell == nil){
cell = [[ProductListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:productListTableViewCell];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
IndexedButton *btn_SelectItem = [IndexedButton buttonWithType:UIButtonTypeCustom];
btn_SelectItem.frame = CGRectMake(10,52,32,32);
[btn_SelectItem setBackgroundImage:[UIImage imageNamed:#"uncheckMark"] forState:UIControlStateNormal];
[btn_SelectItem addTarget:self action:#selector(selectItemAction:)forControlEvents:UIControlEventTouchUpInside];
btn_SelectItem.index = (int)indexPath.row;
btn_SelectItem.tag = TAG_SELECTEDITEM;
[cell addSubview:btn_SelectItem];
}
IndexedButton *btn_SelectItem = (IndexedButton *)[cell viewWithTag:TAG_SELECTEDITEM];
btn_SelectItem.index = (int)indexPath.row;
cell.backgroundColor = [UIColor clearColor];
return cell;
}
#All
Need suggestion, how to go forward to implement the check mark for tableview.
I would suggest you to use cell with accessory view with UITableViewCellAccessoryCheckmark type to show all cells selected/ few cells selected/ none of the cells selected.
Also, you must keep the state for each cell index within a section, whether it's selected or not as
// keeps info for selected rows in a section in mutable index set as
NSMutableIndexSet *selctedCellsInSection;
// initialize the above set instance
selctedCellsInSection = [[NSMutableIndexSet alloc] init];
//Inside cell for row at index path
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
if ([selctedCellsInSection containsIndex:indexPath.row])
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
else
[cell setAccessoryType:UITableViewCellAccessoryNone];
// customize cell as per your requirements
return cell;
}
You need to hold the information about a cell's checkmark whether it needs to be shown or not in selctedCellsInSection set as -
Use [selctedCellsInSection addIndex:rowToSelect]
// to add cell index on which checkmark needs to be shown
Use [selctedCellsInSection removeIndex:rowToUnselect]
// to add cell index on which checkmark should not be shown
After, customizing the data source selctedCellsInSection(which keeps information about selected/ unselected cell) reload the tableview.
Reloading the table will reflect the selected cells with Cell's Accessory Checkmark.
In your case as you need show check mark on all cell, you can do so as-
-(void)showCheckMarkOnAllCells
{
for (int rowIndex = 0; rowIndex < [array_MedicineList count]; rowIndex++)
{
[selctedCellsInSection addIndex: rowIndex];
}
[tableView reloadData];
}
#interface BRNCategoryViewController ()
{
NSMutableArray *arySelectCategory;
NSMutableArray *aryCategory;
}
- (void) viewDidLoad
{
arySelectCategory=[NSMutableArray new];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return aryCategory.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
BRNCategoryCell *cell=[[BRNCategoryCell alloc]initWithOwner:self];
if ([arySelectCategory containsObject:[aryCategory objectAtIndex:indexPath.row]])
{
cell.imgBoxView.image=[UIImage imageNamed:#"checkMark"];
}
else
{
cell.imgBoxView.image=[UIImage imageNamed:#"uncheckMark"];
}
cell.lblTitle.textColor=Rgb2UIColor(127, 127, 127);
cell.lblTitle.font=[ASCustomClass FontWithSize:20.0];
cell.lblTitle.text=aryCategory[indexPath.row];
cell.backgroundColor=[UIColor clearColor];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if ([arySelectCategory containsObject:[aryCategory objectAtIndex:indexPath.row]])
{
[arySelectCategory removeObject:[aryCategory objectAtIndex:indexPath.row]];
}
else
{
[arySelectCategory addObject:[aryCategory objectAtIndex:indexPath.row]];
}
[tblEventCategory reloadData];
}
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 do i get the value (the selected state) from my segmentedcontrols in the tableviewcells?
When i press the button "Get states" it should return the value for each of the segmented controls. I have tried different methods, but I can't find one that works :(
My code so far:
- (void)viewDidLoad
{
[super viewDidLoad];
tableData = [[NSMutableArray alloc] initWithCapacity:0];
tableData = [NSArray arrayWithObjects:#"First", #"Second", #"Third", nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [tableData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = nil;
cell = [tableView dequeueReusableCellWithIdentifier:#"StateCell"];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"StateCell"];
}
//Config cell..
cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
NSArray *itemArray = [NSArray arrayWithObjects: #"1", #"2", #"3", nil];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
segmentedControl.frame = CGRectMake(110, 7, 100, 28);
[cell.contentView addSubview:segmentedControl];
return cell;
[[self tableView] reloadData];
}
- (IBAction)getStates:(id)sender {
// Ruturn the current selected statement, for the individual cell's segmentedcontrol..
// Ex. First = SelectedState 1, Second = SelectedState 0 & Third = SelectedState 2..
}
So what I'm really is asking for; is what the "Get states" button action has to do..
Thanks for your time!
Your code has a couple of problems. Most of them happen because a UITableView reuses its cells.
You are creating a new UISegmentedControl each time a cell is displayed, which you should not. You should create the UISegmentedControl only if you create the cell, move that code into the cell == nil).
You don't have a dataSource that saves the state of the segments. You should not save states in views, especially not if you are dealing with a tableView, because cells are reused.
Here's an example that will get the functionality you need.
// this is an object of your model, it has a title and saves the selected index
#interface MBFancyObject : NSObject
#property (strong, nonatomic) NSString *title;
#property (assign, nonatomic) NSInteger selectedIndex;
#end
#implementation MBFancyObject
#end
#interface MasterViewController () {
NSMutableArray *_objects; // stores instances of MBFancyObject
}
#end
#implementation MasterViewController
- (void)viewDidLoad {
[super viewDidLoad];
// set up the model
_objects = [NSMutableArray array];
for (NSInteger i = 0; i < 6; i++) {
MBFancyObject *object = [[MBFancyObject alloc] init];
object.title = [NSString stringWithFormat:#"Object #%ld", (long)i];
object.selectedIndex = i % 3;
[_objects addObject:object];
}
UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:#"Get States" style:UIBarButtonItemStyleBordered target:self action:#selector(logStates:)];
self.navigationItem.rightBarButtonItem = button;
}
#pragma mark - Table View
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _objects.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"FancyCell"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"FancyCell"];
// add the segmentedControl when you create a new cell
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:#[#"1", #"2", #"3"]];
segmentedControl.frame = CGRectMake(110, 7, 100, 28);
[cell.contentView addSubview:segmentedControl];
// add an action so we can change our model if the view changes
[segmentedControl addTarget:self action:#selector(didChangeSegmentedControl:) forControlEvents:UIControlEventValueChanged];
// use a tag so we can retrieve the segmentedControl later
segmentedControl.tag = 42;
}
// either if the cell could be dequeued or you created a new cell,
// segmentedControl will contain a valid instance
UISegmentedControl *segmentedControl = (UISegmentedControl *)[cell.contentView viewWithTag:42];
MBFancyObject *object = _objects[indexPath.row];
cell.textLabel.text = object.title;
segmentedControl.selectedSegmentIndex = object.selectedIndex;
return cell;
}
- (IBAction)didChangeSegmentedControl:(UISegmentedControl *)sender {
// transform the origin of the cell to the frame of the tableView
CGPoint senderOriginInTableView = [self.tableView convertPoint:CGPointZero fromView:sender];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:senderOriginInTableView];
NSAssert(indexPath, #"must have a valid indexPath");
MBFancyObject *object = _objects[indexPath.row];
object.selectedIndex = sender.selectedSegmentIndex;
}
- (IBAction)logStates:(id)sender {
// query the model, not the view
for (NSInteger i = 0; i < [_objects count]; i++) {
MBFancyObject *object = _objects[i];
NSLog(#"Object \"%#\" - %ld", object.title, (long)object.selectedIndex);
// since you have only one section, each indexPath is 0,i
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
}
}
#end
Use an array to store all the segment control values, and when click one segment control then just change the value correspondingly.
You have serious problem with reusing here
Do not ever allocate a new UI element in tableView:cellForRowAtIndexPath: method unless it is in the if condition if (cell == nil)
Change What in Your tableView:cellForRowAtIndexPath: to be
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"StateCell"];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"StateCell"];
// Add the Segmented Control
NSArray *itemArray = [NSArray arrayWithObjects: #"1", #"2", #"3", nil];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
segmentedControl.frame = CGRectMake(110, 7, 100, 28);
segmentedControl.tag = 1;
[cell addSubview:segmentedControl];
}
//Config cell..
cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
// Get that Segmented Control
UISegmentedControl *segmentedControl = (UISegmentedControl *)[cell viewWithTag:1];
segmentedControl.selectedSegmentIndex = 0; // Set your default value here or add your data in an array and read from that array
return cell;
Then in the action of the button do that
for (UITableViewCell *cell in [tableView visibleCells]) {
UISegmentedControl *segmentedControl = (UISegmentedControl *)[cell viewWithTag:1];
NSLog(#"%d",segmentedControl.selectedSegmentIndex);
}
However this code is not perfect unless you have only 3 cells in your table to avoid reuse or visibility problem