What i am doing is , I have an UITableview and i added UIButton as a custom view . I am giving tag to each button and tag got received in the action method. When i press the button it change the images for selected and unselected button but when i scroll it , it will come to normal state.
This is my cell for row at index method
static NSString *CellIdentifier = #"Cell4";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [self tableviewCellWithReuseIdentifierFollowing:CellIdentifier];
}
followingButton = [UIButton buttonWithType:UIButtonTypeCustom];
[followingButton addTarget:self action:#selector(followingButtonpressed:)forControlEvents:UIControlEventTouchUpInside];
[followingButton setImage:[UIImage imageNamed:#"following12.png"] forState:UIControlStateNormal];
followingButton.frame = CGRectMake(220.0 ,20.0, 100, 40.0);
[cell.contentView addSubview:followingButton];
NSLog(#"row--%d",indexPath.row);
followingButton.tag=indexPath.row;
NSLog(#"followingButton.tag--%d",followingButton.tag);
[self configureCellFollowing:cell forIndexPath:indexPath];
return cell;
}
==================
//Here is the action method
-(void)followingButtonpressed:(id)sender
{
NSLog(#"sender tag --%d",[sender tag]);
UIButton *btnPly = (UIButton *)sender;
if([btnPly isSelected])
{
[btnPly setSelected:NO];
[btnPly setImage:[UIImage imageNamed:#"following12.png"] forState:UIControlStateNormal];
}
else
{
[btnPly setSelected:YES];
[btnPly setImage:[UIImage imageNamed:#"following_off12.png"] forState:UIControlStateNormal];
}
}
Note : This code create cell for each row of data (Not reuse cell)
You need to change only as describe , May be helpful for you
NSString *CellIdentifier = [NSString stringWithFormat:#"S%1dR%1d",indexPath.section,indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
may be solve your problem :)
The reason your buttons are "resetting" is because tableView:cellForRowAtIndexPath gets called multiple times (whenever a cell is about to be visible).
Each time this gets called you are reinitializing your button and resetting the image to following12.png (the default state). That's why when you scroll the buttons appear to reset.
You can't rely on the cell itself to preserve state because the cell will get reset every time. You need to move your state somewhere else (like in an array instance variable). Then when you have to configure a new cell in tableView:cellForRowAtIndexPath you can initialize it to the proper state (based on the array).
So create an NSMutableArray instance variable called myStateArray (or whatever) to store your button states, then your cellForRowAtIndexPath should look more like:
static NSString *CellIdentifier = #"Cell4";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [self tableviewCellWithReuseIdentifierFollowing:CellIdentifier];
}
followingButton = [UIButton buttonWithType:UIButtonTypeCustom];
[followingButton addTarget:self action:#selector(followingButtonpressed:)forControlEvents:UIControlEventTouchUpInside];
// -- Fetch the state from your array
BOOL buttonPressed = [[self.myStateArray objectAtIndex:indexPath.row] boolValue];
// -- Initialize the button state correctly
[followingButton setSelected:buttonPressed];
if (buttonPressed) {
[followingButton setImage:[UIImage imageNamed:#"following12.png"] forState:UIControlStateNormal];
} else {
[followingButton setImage:[UIImage imageNamed:#"following_off12.png"] forState:UIControlStateNormal];
}
followingButton.frame = CGRectMake(220.0 ,20.0, 100, 40.0);
[cell.contentView addSubview:followingButton];
NSLog(#"row--%d",indexPath.row);
followingButton.tag=indexPath.row;
NSLog(#"followingButton.tag--%d",followingButton.tag);
[self configureCellFollowing:cell forIndexPath:indexPath];
return cell;
}
Then in your button press make sure to save the state:
-(void)followingButtonpressed:(id)sender
{
// -- Save the state
[self.myStateArray insertObject:[NSNumber numberWithBool:[btnPly isSelected]] atIndex:[sender tag]];
NSLog(#"sender tag --%d",[sender tag]);
UIButton *btnPly = (UIButton *)sender;
if([btnPly isSelected])
{
[btnPly setSelected:NO];
[btnPly setImage:[UIImage imageNamed:#"following12.png"] forState:UIControlStateNormal];
}
else
{
[btnPly setSelected:YES];
[btnPly setImage:[UIImage imageNamed:#"following_off12.png"] forState:UIControlStateNormal];
}
}
As I understand from code you create UIButton every time when UITableView asks for cell. In both cases if you create a new cell or you use dequeued one. Then you create and add one more button every time over already created one. Move button creation to cell creation if So your cellForRowAtIndexPath method should looks like
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell4";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [self tableviewCellWithReuseIdentifierFollowing:CellIdentifier];
followingButton = [UIButton buttonWithType:UIButtonTypeCustom];
[followingButton addTarget:self action:#selector(followingButtonpressed:)forControlEvents:UIControlEventTouchUpInside];
[followingButton setImage:[UIImage imageNamed:#"following12.png"] forState:UIControlStateNormal];
followingButton.frame = CGRectMake(220.0 ,20.0, 100, 40.0);
[cell.contentView addSubview:followingButton];
}
NSLog(#"row--%d",indexPath.row);
followingButton.tag=indexPath.row;
NSLog(#"followingButton.tag--%d",followingButton.tag);
[self configureCellFollowing:cell forIndexPath:indexPath];
return cell;
}
But this will not be competed solution of your problem. As you probably know UITableView uses "reusable" cells to decrease system memory usage. It uses only amount of cells as it necessary to show at the moment. So in table with 100 cells it will create actually about 10. And all of them wont store correct state of all amount pressed/unpressed buttons. To achieve correct behaviour you have to refuse using tags and use some model logic instead. Easiest way - NSMutableArray where you will store buttons states. In followingButtonpressed: method you will set proper object to YES/NO and in cellForRowAtIndexPath you will read this value.
Check code below
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell4";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [self tableviewCellWithReuseIdentifierFollowing:CellIdentifier];
followingButton = [UIButton buttonWithType:UIButtonTypeCustom];
[followingButton addTarget:self action:#selector(followingButtonpressed:)forControlEvents:UIControlEventTouchUpInside];
[followingButton setImage:[UIImage imageNamed:#"following12.png"] forState:UIControlStateNormal];
followingButton.frame = CGRectMake(220.0 ,20.0, 100, 40.0);
[cell.contentView addSubview:followingButton];
BOOL isSelected = [[statesArray objectAtIndex:btnPly.tag] boolValue];
[self setState:isSelected forButton:followingButton];
}
NSLog(#"row--%d",indexPath.row);
followingButton.tag=indexPath.row;
NSLog(#"followingButton.tag--%d",followingButton.tag);
[self configureCellFollowing:cell forIndexPath:indexPath];
return cell;
}
-(void)followingButtonpressed:(id)sender
{
NSLog(#"sender tag --%d",[sender tag]);
UIButton *btnPly = (UIButton *)sender;
BOOL isSelected = [[statesArray objectAtIndex:btnPly.tag] boolValue];
[statesArray replaceObjectAtIndex:btnPly.tag withObject:[NSNumber numberWithBool:!isSelected]];
if(isSelected)
{
[self setState:NO forButton:btnPly];
}
else
{
[self setState:YES forButton:btnPly];
}
}
- (void) setState:(BOOL)state forButton:(UIButton *)button
{
if(state)
{
[button setSelected:NO];
[button setImage:[UIImage imageNamed:#"following12.png"] forState:UIControlStateNormal];
}
else
{
[button setSelected:YES];
[button setImage:[UIImage imageNamed:#"following_off12.png"] forState:UIControlStateNormal];
}
}
Where statesArray is
NSMutableArray *statesArray = [NSMutableArray new];
and you have to create and initialize it somewhere in you class. Count of objects in statesArray has to be the same as count of cells int tableView.
This is because every time when you are scrolling then this code calling
[followingButton setImage:[UIImage imageNamed:#"following12.png"] forState:UIControlStateNormal];
so check now
static NSString *CellIdentifier = #"Cell4";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [self tableviewCellWithReuseIdentifierFollowing:CellIdentifier];
followingButton = [UIButton buttonWithType:UIButtonTypeCustom];
[followingButton addTarget:self action:#selector(followingButtonpressed:)forControlEvents:UIControlEventTouchUpInside];
[followingButton setImage:[UIImage imageNamed:#"following12.png"] forState:UIControlStateNormal];
followingButton.frame = CGRectMake(220.0 ,20.0, 100, 40.0);
[cell.contentView addSubview:followingButton];
[self configureCellFollowing:cell forIndexPath:indexPath];
}
return cell;
}
Related
I need to add a UIButton in my UITableView only with my first and last array count. I found that we can use tableFooterView, to add unbutton below our tableview. But how can I achieve this over my tableview and only with first and last array values? Here is my code,
- (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];
}
//Adding a UIButton in last row
NSInteger lastSectionIndex = [editTable numberOfSections] - 1;
NSLog(#"lastSectionIndex:%d",lastSectionIndex);
// Then grab the number of rows in the last section
NSInteger lastRowIndex = [editTable numberOfRowsInSection:lastSectionIndex] - 1;
NSLog(#"lastRowIndex:%d",lastRowIndex);
// Now just construct the index path
NSIndexPath *pathToLastRow = [NSIndexPath indexPathForRow:lastRowIndex inSection:lastSectionIndex];
NSLog(#"last index:%#",pathToLastRow);
if (pathToLastRow.row == lastRowIndex)
{
NSLog(#"row enters");
checkButton1 = [UIButton buttonWithType:UIButtonTypeCustom];
[checkButton1 setFrame:CGRectMake(200, 0, 168, 168)];
[checkButton1 addTarget:self
action:#selector(customActionPressed:)
forControlEvents:UIControlEventTouchDown];
[checkButton1 setBackgroundImage:[[UIImage imageNamed:#"Up Arrow.jpg"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:0.0] forState:UIControlStateNormal];
editTable.tableFooterView = checkButton1;
[cell addSubview:checkButton1];
}
Now I receive the buttons in every cell of my tableview. How can I give the button only to my first and last row array values? Thanks in advance.
Change your if condition as,
if ((lastSectionIndex == indexPath.section && lastRowIndex == indexPath.row ) || (indexPath.section == 0 && indexPath.row == 0 ))
{
It will look like this,
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
UIButton *checkButton1 = [UIButton buttonWithType:UIButtonTypeCustom];
checkButton1.tag = 100;//not recommended, I would suggest to use custom UITableViewCell class and add this button as subview inside its init method
[checkButton1 setFrame:CGRectMake(200, 0, 168, 168)];
[checkButton1 addTarget:self
action:#selector(customActionPressed:)
forControlEvents:UIControlEventTouchDown];
[checkButton1 setBackgroundImage:[[UIImage imageNamed:#"Up Arrow.jpg"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:0.0] forState:UIControlStateNormal];
[cell addSubview:checkButton1];
}
//Adding a UIButton in last row
NSInteger lastSectionIndex = [editTable numberOfSections] - 1;
NSLog(#"lastSectionIndex:%d",lastSectionIndex);
// Then grab the number of rows in the last section
NSInteger lastRowIndex = [editTable numberOfRowsInSection:lastSectionIndex] - 1;
NSLog(#"lastRowIndex:%d",lastRowIndex);
// Now just construct the index path
NSIndexPath *pathToLastRow = [NSIndexPath indexPathForRow:lastRowIndex inSection:lastSectionIndex];
NSLog(#"last index:%#",pathToLastRow);
UIButton *checkButton1 = (UIButton *)[cell viewWithTag:100];//not recommended, I would suggest to use custom UITableViewCell class and add this button as subview inside its init method
if ((lastSectionIndex == indexPath.section && lastRowIndex == indexPath.row ) || (indexPath.section == 0 && indexPath.row == 0 ))
{
checkButton1.hidden = NO;
} else {
checkButton1.hidden = YES;
}
You dont have to declare checkButton1 in .h file. Make it a local variable as shown above. Then you can set hidden property to hide/show in difference cells. Instead of doing the above, you can also create this button in custom UITableViewCell class and set the hidden property as cell.checkButton1.hidden = YES. You need to subclass UITableViewCell for that.
instead of creating Button in CellforRow You can Create in ViewDidload And attach it with FooterView of table.
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[aButton setTitleColor:[UIColor colorWithWhite:0.0 alpha:0.56] forState:UIControlStateDisabled];
[aButton setBackgroundImage:[[UIImage imageNamed:#"test.png"] stretchableImageWithLeftCapWidth:kButtonSliceWidth topCapHeight:0] forState:UIControlStateNormal];
[aButton setTitle:#"Click me" forState:UIControlStateNormal];
[aButton.titleLabel setFont:[UIFont boldSystemFontOfSize:kFontSize14]];
[aButton setFrame:CGRectMake(10.0, 15.0, 300.0, 44.0)];
[self.tableView setTableFooterView:aButton];
Same thing you can do for headerview. or else You Can Use Viewforheader method
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0,0, 320, 44)] autorelease]; // x,y,width,height
UIButton *reportButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
reportButton.frame = CGRectMake(80.0, 0, 160.0, 40.0); // x,y,width,height
[reportButton setTitle:#"rep" forState:UIControlStateNormal];
[reportButton addTarget:self
action:#selector(buttonPressed:)
forControlEvents:UIControlEventTouchDown];
[headerView addSubview:reportButton];
return headerView;
}
You should add first button to your table view Header And other button should be added to your footer view Secion of tableView
i am using custom checkbox buttons in my table view and want to save the selected cell's data to a mutable array.... can anyone help me... Thanks
create a mutable array to store your selected data, lets call it 'yourSeparatedData' , set the tag of your checkbox in cellForRowAtIndexPath and set onCheck: method as target. the code will look like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = #"setMe";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyle………
}
checkBox = [UIButton buttonWithType:UIButtonTypeRoundedRect];
checkBox.frame = CGRectMake(customizeMe);
if(yourSeparatedData && [yourSeparatedData indexOfObject:[yourTableViewDataSource objectAtIndex:indexPath.row]] != NSNotFound)
{
[checkBox setBackgroundImage:[UIImage imageNamed:#"check.png"] forState:UIControlStateNormal];
}
else {
[checkBox setBackgroundImage:[UIImage imageNamed:#"unCheck.png"] forState:UIControlStateNormal];
}
[checkBox addTarget:self action:#selector(onCheck:) forControlEvents:UIControlEventTouchUpInside];
[checkBox setTag:indexPath.row];
[cell addSubview:checkBox];
return cell;
}
-(void)onCheck:(id)sender {
if(yourSeparatedData && [yourSeparatedData indexOfObject:[yourTableViewDataSource objectAtIndex:[sender tag]]] != NSNotFound)
{
[sender setBackgroundImage:[UIImage imageNamed:#"unCheck.png"] forState:UIControlStateNormal];
[yourSeparatedData removeObject:[yourTableViewDataSource objectAtIndex:[sender tag]]];
}
else {
[sender setBackgroundImage:[UIImage imageNamed:#"check.png"] forState:UIControlStateNormal];
[yourSeparatedData addObject:[yourTableViewDataSource objectAtIndex:[sender tag]]];
}
[yourTableView reloadData];
}
this code is not tested, you are using checkbox so I assumed that you want to separate not just one data, at the end of the selection, you will have 'yourSeparatedData' with the objects picked from your tableView.
you can try custom action in UITableView cell for button prees,you can also use put a check box image and on click you can change the image as checked here is the code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath{
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:#"identifire"];
cell=[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"identifire"] autorelease];
cell.detailTextLabel.text=[id_Array objectAtIndex:indexPath.row];
cell.detailTextLabel.hidden=YES;
button = [UIButton buttonWithType:UIButtonTypeCustom];
NSString *path1 = [[NSBundle mainBundle] pathForResource:#"n_cross" ofType:#"png"];
UIImage *buttonImage1 = [[UIImage alloc] initWithContentsOfFile:path1];
[button setImage:buttonImage1 forState:UIControlStateNormal];
[button addTarget:self
action:#selector(customActionPressed:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Custom Action" forState:UIControlStateNormal];
button.frame = CGRectMake(245.0f, 20.0f, 40.0f, 40.0f);
[cell addSubview:button];
[buttonImage1 release];
CGRect imageFrame=CGRectMake(10,8,50,50);
self.cellimage=[[[UIImageView alloc] initWithFrame:imageFrame] autorelease];
self.cellimage.image=[imageIdArray objectAtIndex:indexPath.row];
[cell.contentView addSubview:self.cellimage];
return cell;
}
-(void)customActionPressed :(id)sender
{
//Get the superview from this button which will be our cell
UITableViewCell *owningCell = (UITableViewCell*)[sender superview];
NSIndexPath *cell = [_tableView indexPathForCell:owningCell];
NSString *uid=[id_Array objectAtIndex:cell.row];
[id_Array removeObjectAtIndex:cell.row];
[_tableView reloadData];
[self performSelectorInBackground:#selector(ignoreRequest:) withObject:uid];
}
here i have an id_Array and on selection of a cell i just remove the object at that index
You have to do this manually, there is no facility in a UITableView or UITableViewController t o do this automatically.
When user selects any cell then in didSelectRowAtIndexPath you can add selected object dynamically.
[someMutableArr addObject:[tableArr objectAtIndex:indexPath.row]];
Try this
- (void)onButtonClick {
int numberOfSections = [tableView numberOfSections];
for (int section = 0; section < numberOfSections; section++) {
int numberOfRows = [tableView numberOfRowsInSection:section];
for (int row = 0; row < numberOfRows; row++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
// Cell is selected
//here you can add that values into an array
} else {
// Cell is not selected
}
}
}
}
I have a tableview where I am displaying my values from database in tableview cells. In this tableview cellforrowatindexpath, I have created a button with an image on it and set selector for it. So when I click on the button my selector is called and it changes my image to another image.
But the problem is it does not identifies the indexpath i.e. if 4 rows are present in the tableview and if I click on the first row button, its image should change but problem is 4th row action is performed and its image is changed because it does not get the proper indexpath of the image to change.
This is my cellforrowatindexpath code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = [NSString stringWithFormat:#"Cell%d%d", indexPath.section, indexPath.row];
appDelegate = (StopSnoozeAppDelegate*)[[UIApplication sharedApplication]delegate];
cell =(TAlarmCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[TAlarmCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
mimageButton = [UIButton buttonWithType:UIButtonTypeCustom];
mimageButton.frame=CGRectMake(10, 20, 20, 20);
mimageButton.tag = 1;
onButtonView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 50)];
onButtonView.tag = 2;
onButtonView.image = [UIImage imageNamed:#"alarm_ON.png"];
[mimageButton setImage:onButtonView.image forState:UIControlStateNormal];
[cell.contentView addSubview:mimageButton];
[mimageButton addTarget:self action:#selector(changeMapType::) forControlEvents:UIControlEventTouchUpInside];
}
return cell;
}
This is my changemapType code
-(void)changeMapType:(NSIndexPath*)path1:(UIButton*)sender{
appDelegate.changeimagetype =!appDelegate.changeimagetype;
if(appDelegate.changeimagetype == YES)
{
onButtonView.image = [UIImage imageNamed:#"alarm_OF.png"];
[mimageButton setImage:onButtonView.image forState:UIControlStateNormal];
appDelegate.changeimagetype = YES;
}
else
{
onButtonView.image = [UIImage imageNamed:#"alarm_ON.png"];
[mimageButton setImage:onButtonView.image forState:UIControlStateNormal];
appDelegate.changeimagetype = NO;
}
}
Don't break table view cell reuse just to put a different tag on each button. If your cells are the same, use the same reuse identifier.
You can find out the index path of the sender like this, without any need to mess around with tags. It also works for multi section tables.
CGPoint hitPoint = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *hitIndex = [self.tableView indexPathForRowAtPoint:hitPoint];
I don't think you can have additional arguments in an #selector like that. What you might have to do is subclass UIButton and add an NSIndexPath property (or even just an int) and in -(void)changeMapType:(MyCustomButton*)sender access the property there.
Also it seems you do not even use the index path in changeMapType so that will need to be changed as well.
EDIT: Is it the button image you are trying to change? In which case you don't need the index path at all, or a subclass. Just use [sender setImage:(UIImage *)image forState:(UIControlState)state].
Use yourTableView for getting the Index Path.. Try something like this.
- (void)buttonAction:(UIButton*)sender {
UITableViewCell *cell = (UITableViewCell*)button.superview;
NSIndexPath *indexPath = [yourTableView indexPathForCell:cell];
NSLog(#"%d",indexPath.row)
}
I think following code might help you..
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIView *myCheckbox = [[UIView alloc] init];
UIButton *myBt1 = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 30, 30)];
if([appDelegate.changeimagetype == YES"]){
[myBt1 setBackgroundImage:[UIImage imageNamed:#"alarm_ON.png"] forState:UIControlStateNormal];
}
else {
[myBt1 setBackgroundImage:[UIImage imageNamed:#"alarm_OF.png"] forState:UIControlStateNormal];
}
[myBt1 addTarget:self action:#selector(btcheckbox:) forControlEvents:UIControlEventTouchDown];
[myBt1 setTag:indexPath.row];
[myCheckbox addSubview:myBt1];
[myBt1 release];
[myCheckbox release];
[cell addsubview:myview];
return cell;
}
-(void) btcheckbox:(id) sender
{
UIButton *currentButton = (UIButton *) sender;
if([[currentButton backgroundImageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:#"alarm_OF.png"]])
{
appDelegate.changeimagetype = YES;
[currentButton setBackgroundImage:[UIImage imageNamed:#"alarm_ON.png"] forState:UIControlStateNormal];
}else if([[currentButton backgroundImageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:#"alarm_ON.png"]])
{
appDelegate.changeimagetype = NO;
[currentButton setBackgroundImage:[UIImage imageNamed:#"alarm_OF.png"] forState:UIControlStateNormal];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = [NSString stringWithFormat:#"Cell%d", indexPath.row];
appDelegate = (StopSnoozeAppDelegate*)[[UIApplication sharedApplication]delegate];
cell =(TAlarmCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[TAlarmCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
UIButton *mimageButton = [UIButton buttonWithType:UIButtonTypeCustom];
mimageButton.frame=CGRectMake(10, 20, 20, 20);
mimageButton.tag = indexPath.row;
//onButtonView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 50)];
//onButtonView.tag = 2;
// onButtonView.image = [UIImage imageNamed:#"alarm_ON.png"];
[mimageButton setImage:[UIImage imageNamed:#"alarm_ON.png"] forState:UIControlStateNormal];
mimageButton.selected = NO;
[cell.contentView addSubview:mimageButton];
[mimageButton addTarget:self action:#selector(changeMapType:) forControlEvents:UIControlEventTouchUpInside];
}
return cell;
}
-(void)changeMapType:(UIButton*)sender{
if(sender.selected == YES)
{
// onButtonView.image = [UIImage imageNamed:#"alarm_OF.png"];
[sender setImage:[UIImage imageNamed:#"alarm_ON.png"] forState:UIControlStateNormal];
sender.selected = NO;
}
else
{
//onButtonView.image = [UIImage imageNamed:#"alarm_ON.png"];
[sender setImage:[UIImage imageNamed:#"alarm_OF.png"] forState:UIControlStateNormal];
sender.selected = YES;
}
}
I have a UITableView and i programatically add two buttons to the cell. 1 button adds to the cells text ( counts up ) the other subtracts 1 (counts down). However, lets say i add 4, the cell's text will be 4, but when i scroll that cell up and out of the view, when it comes back down into view, the cells text is back to 1 which is where it started out. The same happens if i add(it does the same if i subtract also) to the cells text and switch pages and then go back to the table view. Here is the cellForRow:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
newBtn = [[UIButton alloc]init];
newBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[newBtn setFrame:CGRectMake(260,20,55,35)];
[newBtn addTarget:self action:#selector(subtractLabelText:) forControlEvents:UIControlEventTouchUpInside];
[newBtn setTitle:#"-" forState:UIControlStateNormal];
[newBtn setEnabled:YES];
[cell addSubview:newBtn];
subBtn = [[UIButton alloc]init];
subBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[subBtn setFrame:CGRectMake(200,20,55,35)];
[subBtn addTarget:self action:#selector(addLabelText:) forControlEvents:UIControlEventTouchUpInside];
[subBtn setTitle:#"+" forState:UIControlStateNormal];
[subBtn setEnabled:YES];
[cell addSubview:subBtn];
}
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
cell.imageView.image = [imageArray objectAtIndex:indexPath.row];
cell.textLabel.text = [cells objectAtIndex:indexPath.row];
return cell;
}
Any and all help is appreciated! Thanks:D
Methods for buttons
- (IBAction)addLabelText:(id)sender{
cell = (UITableViewCell*)[sender superview];
cell.textLabel.text = [NSString stringWithFormat:#"%d",[cell.textLabel.text intValue] +1];
}
- (IBAction)subtractLabelText:(id)sender
{
cell = (UITableViewCell*)[sender superview];
if ( [[cell.textLabel text] intValue] == 0){
cell.textLabel.text = [NSString stringWithFormat:#"%d",[cell.textLabel.text intValue] +0];
}
else{
cell.textLabel.text = [NSString stringWithFormat:#"%d",[cell.textLabel.text intValue] -1];
//[myTableView reloadData];
}
}
You need something like this, where you are storing the values outside the cells. This is because the cells get reused and are not good long term storage.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
subBtn = [[UIButton alloc]init];
subBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[subBtn setFrame:CGRectMake(200,20,55,35)];
[subBtn addTarget:self action:#selector(addLabelText:indexPath.row) forControlEvents:UIControlEventTouchUpInside];
[subBtn setTitle:#"+" forState:UIControlStateNormal];
[subBtn setEnabled:YES];
[cell addSubview:subBtn];
}
// we're loading the value from the array each time the cell is displayed.
cell.textLabel.text = [cellLabelValues objectAtIndex:indexPath.row];
return cell;
}
- (IBAction)addLabelText:(int)currentRow{
NSString *newValue = [NSString stringWithFormat:#"%d",[[[cellLabelValues objectAtIndex:currentRow] intValue] +1];
// we update the value in the array since this is the source of the data for the cell
[cellLabelValues replaceObjectAtIndex:currentRow withObject:newValue];
// now reload to get the new value
[myTableView reloadData];
}
I know xcode don't have radio Button
so I try to add a custom button and make it action like a radio button
This is the image I use
and this is the code I set to cell
UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];
[but setImage:[UIImage imageNamed:#"radio-off.png"] forState:UIControlStateNormal];
[but setImage:[UIImage imageNamed:#"radio-on.png"] forState:UIControlStateSelected];
[but setFrame:CGRectMake(0, 0, 44, 44)];
[but addTarget:self action:#selector(radioButton:) forControlEvents:UIControlEventTouchUpInside];
cell.accessoryView= but;
and this is the problem I want to ask is
how can I give a void in - (IBAction)radioButton:(UIButton *)button
To control Two Radio Button in Two Rows
If Row 1 Radio button's selected is YES
btn in row 2 will be btn.state=NO and won't response the
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
It will be like this pic
How to set the if conditions in - (IBAction)radioButton:(UIButton *)button
this pic is fake...I only add the button in the cell...and changed the text color
Great Thanks to all stack overflow friends~
OK..here is how I add a button into a tableview :
in tableviewController.h :
#interface RootViewController : UITableViewController {
NSMutableArray *radioButtonArray;
}
#property (nonatomic ,retain)NSMutableArray *radioButtonArray;
in tableviewController.h.m
- (void)viewDidAppear:(BOOL)animated {
radioButtonArray = [NSMutableArray new];
for (int i = 0; i < 30; i ++) {
UIButton *radioButton = [UIButton buttonWithType:UIButtonTypeCustom];
[radioButton setImage:[UIImage imageNamed:#"radio-off.png"] forState:UIControlStateNormal];
[radioButton setImage:[UIImage imageNamed:#"radio-on.png"] forState:UIControlStateSelected];
[radioButton setFrame:CGRectMake(0, 0, 44, 44)];
[radioButton addTarget:self action:#selector(radioButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[radioButtonArray addObject:radioButton];
}
[super viewDidAppear:animated];
}
and give it a (IBAction) void
- (IBAction)radioButtonPressed:(UIButton *)button{
[button setSelected:YES];
// Unselect all others.
for (UIButton *other in radioButtonArray) {
if (other != button) {
other.selected=NO;
}
}
}
than you can add your button into the cell
- (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] autorelease];
}
cell.accessoryView = [radioButtonArray objectAtIndex:[indexPath row]];
// Configure the cell.
return cell;
}
You will need an array of all the radio buttons. Remember that table cells get recycled/may not be visible, etc. so create an array just with the buttons and then grab the right button out of that array in your tableView:cellForIndexPath: method.
So in your tableView:cellForIndexPath: method you would do something like this:
cell.accessoryView = [myButtonArray objectAtIndex:[indexPath row]];
Then, in your radioButton: radioButtonPressed: method you would do:
// Select the pressed button.
[button setSelected:YES];
// Unselect all others.
for (UIButton *other in myButtonArray) {
if (other != button) {
[other setSelected:NO];
}
}