i am working with Storybord and i got a tableview with a checkboxbutton.
and i am using NSUserDefaults to save the state of my checkboxbutton i tried to save it with Core Data but i dont know how so its better to go to the easy way NSUserDefaults .
and the checkboxbutton is working great but the problem it does not save the state of the checkboxbutton !!!
when i close the app and open it again its not saved .
can any one please help me here i did all my best to solve this problem but no luck
here is my code
#property (strong, nonatomic) IBOutlet UIButton *myButton;
#property (nonatomic,assign) BOOL checked;
#synthesize myButton,checked;
- (void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
checked = [defaults boolForKey:#"boxIsChecked"];
[defaults synchronize];
[self checkTheBox];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
NSManagedObject *device = [self.Work objectAtIndex:indexPath.row];
[cell.textLabel setText= [Work valueForKey:#"name"]
myButton = [UIButton buttonWithType:UIButtonTypeCustom] ;
[myButton setFrame:CGRectMake(260,2,40,40)];
myButton.tag = indexPath.row;
[myButton setImage:[UIImage imageNamed:#"checkBox.png"] forState:UIControlStateNormal];
[myButton addTarget:self action:#selector(ButtonCheckMark:)
forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:myButton];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
- (IBAction)ButtonCheckMark:(id)sender {
myButton = (UIButton *)sender;
NSLog(#"playButton %li" , (long)myButton.tag);
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (!checked) {
[myButton setImage:
[UIImage imageNamed:#"checkBoxMarked.png"] forState:UIControlStateNormal];
checked = YES;
[defaults setBool:checked forKey:#"boxIsChecked"];
}
else if (checked) {
[myButton setImage:
[UIImage imageNamed:#"checkBox.png"] forState:UIControlStateNormal];
checked = NO;
[defaults setBool:checked forKey:#"boxIsChecked"];
}
[defaults synchronize];
}
- (void) checkTheBox {
if (!checked) {
[myButton setImage:
[UIImage imageNamed:#"checkBox.png"] forState:UIControlStateNormal];
}
else if (checked) {
[myButton setImage:
[UIImage imageNamed:#"checkBoxMarked.png"] forState:UIControlStateNormal];
}
}
Related
Here is my problem, i have a custom cell in that 1 label and 4 buttons like question and answers,when the user click on the button 1 remaining 3 button go like this,
When the user scroll the cell it is not saving the what the user selected button i mean to say user click on the what ever the button it is not saving.
Here is my code,
ViewDidLoad()
{
testArray = [[NSMutableArray alloc]init];
for (int i =0; i<[mainArray count]; i++)
{
[testArray addObject:#"Unchecked"];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellId = #"Cell";
ContestQATableViewCell *cell =(ContestQATableViewCell *)[tableViewQA dequeueReusableCellWithIdentifier:cellId];
if (cell==nil)
{
NSArray *myNib;
myNib =[[NSBundle mainBundle]loadNibNamed:#"ContestQATableViewCell" owner:self options:nil];
cell = (ContestQATableViewCell *)[myNib lastObject];
}
cell.textLabel.text = [mainArray objectAtIndex:indexPath.row];
if([[testArray objectAtIndex:indexPath.row] isEqualToString:#"Unchecked"])
[cell.answer1 setImage:[UIImage imageNamed:#"RadioUnChecked"] forState:UIControlStateNormal];
else
[cell.answer1 setImage:[UIImage imageNamed:#"RadioChecked"] forState:UIControlStateNormal];
cell.answer1.tag = indexPath.row;
[cell.answer1 addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:cell.answer1];
return cell;
[cell.answer1 addTarget:self action:#selector(buttonsClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.answer2 addTarget:self action:#selector(buttonsClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.answer3 addTarget:self action:#selector(buttonsClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.answer4 addTarget:self action:#selector(buttonsClicked:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
and here is my add target method
-(void)buttonsClicked:(id)sender
{
UIButton *btn=(UIButton *)sender;
ContestQATableViewCell * cell=(ContestQATableViewCell *) [btn.superview superview];
if (cell.answer1.tag==btn.tag)
{
[cell.answer1 setImage:[UIImage imageNamed:#"RadioChecked"] forState:UIControlStateNormal];
}else{
[cell.answer1 setImage:[UIImage imageNamed:#"RadioUnChecked"] forState:UIControlStateNormal];
}
if (cell.answer2.tag==btn.tag)
{
[cell.answer2 setImage:[UIImage imageNamed:#"RadioChecked"] forState:UIControlStateNormal];
}else{
[cell.answer2 setImage:[UIImage imageNamed:#"RadioUnChecked"] forState:UIControlStateNormal];
}
if (cell.answer3.tag==btn.tag)
{
[cell.answer3 setImage:[UIImage imageNamed:#"RadioChecked"] forState:UIControlStateNormal];
}else{
[cell.answer3 setImage:[UIImage imageNamed:#"RadioUnChecked"] forState:UIControlStateNormal];
}
if (cell.answer4.tag==btn.tag)
{
[cell.answer4 setImage:[UIImage imageNamed:#"RadioChecked"] forState:UIControlStateNormal];
}else{
[cell.answer4 setImage:[UIImage imageNamed:#"RadioUnChecked"] forState:UIControlStateNormal];
}
}
For Check-Uncheck functionality only buttonClicked: method is not enough. You will have also put the condition in cellForRowAtIndexPath: method for which button is selected or which in unselected because cellForRowAtIndexPath: method will call each time when you will scroll your UITableView and cells will be refresh.
for example
I explain in step by step
Step-1
Create the two arrays one for gloabally another one for checking purpose
#interface ViewController : UIViewController<UITableViewDelegate, UITableViewDataSource>
{
NSMutableArray *arrayforCheckUnchek; // handle which button is selected or which is unselected
NSMutableArray *originalArray; // original Array
}
Step-2
allocating the memory for arrays
- (void)viewDidLoad
{
[super viewDidLoad];
arrayforCheckUnchek = [[NSMutableArray alloc]init];
originalArray = [[NSMutableArray alloc]initWithObjects:#"cell1",#"cell2",#"cell3",#"cell4",#"cell5", nil];
// setting all cell initilayy at un check
for(int i=0; i<[originalArray count]; i++)
{
[arrayforCheckUnchek addObject:#"Unchecked"];
}
}
Step-2
setup your datasource Methods
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [originalArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *Identifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
if(cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [originalArray objectAtIndex:indexPath.row];
UIButton *radiobutton = [UIButton buttonWithType:UIButtonTypeCustom];
[radiobutton setFrame:CGRectMake(270.0, 7.0, 30.0, 30.0)]; // customize the frames
if([[arrayforCheckUnchek objectAtIndex:indexPath.row] isEqualToString:#"Unchecked"])
[radiobutton setImage:[UIImage imageNamed:#"RadioUnChecked"] forState:UIControlStateNormal];
else
[radiobutton setImage:[UIImage imageNamed:#"RadioChecked"] forState:UIControlStateNormal];
radiobutton.tag = indexPath.row;
[radiobutton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:radiobutton];
return cell;
}
Step-3
here selected button index you can change the image
-(void)buttonClicked:(UIButton *)sender
{
//Getting the indexPath of cell of clicked button
CGPoint touchPoint = [sender convertPoint:CGPointZero toView:yourtableviewname];
NSIndexPath *indexPath = [yourtableviewname indexPathForRowAtPoint:touchPoint];
//Checking the condition button is checked or unchecked.
if([[arrayforCheckUnchek objectAtIndex:indexPath.row] isEqualToString:#"Unchecked"])
{
[sender setImage:[UIImage imageNamed:#"RadioChecked"] forState:UIControlStateNormal];
[arrayforCheckUnchek replaceObjectAtIndex:indexPath.row withObject:#"Checked"];
}
else
{
[sender setImage:[UIImage imageNamed:#"RadioUnChecked"] forState:UIControlStateNormal];
[arrayforCheckUnchek replaceObjectAtIndex:indexPath.row withObject:#"Unchecked"];
}
}
in my custom cell lot of question and answers are there, in each section i want to select any one button,that button how can store it? in CellForRowAtIndexPath i created targets for each answer,
here is my code!
-(void)buttonsClicked:(id)sender
{
UIButton *btn=(UIButton*)sender;
ContestQATableViewCell * cell=(ContestQATableViewCell *)[btn.superview superview];
if (cell.answer1.tag==btn.tag)
{
NSLog(#"%ld",(long)btn.tag);
[cell.answer1 setImage:[UIImage imageNamed:#"RadioChecked"] forState:UIControlStateNormal];
}else{
[cell.answer1 setImage:[UIImage imageNamed:#"RadioUnChecked"] forState:UIControlStateNormal];
}
if (cell.answer2.tag==btn.tag)
{
NSLog(#"%ld",(long)btn.tag);
[cell.answer2 setImage:[UIImage imageNamed:#"RadioChecked"] forState:UIControlStateNormal];
}else{
[cell.answer2 setImage:[UIImage imageNamed:#"RadioUnChecked"] forState:UIControlStateNormal];
}
if (cell.answer3.tag==btn.tag)
{
NSLog(#"%ld",(long)btn.tag);
[cell.answer3 setImage:[UIImage imageNamed:#"RadioChecked"] forState:UIControlStateNormal];
}else{
[cell.answer3 setImage:[UIImage imageNamed:#"RadioUnChecked"] forState:UIControlStateNormal];
}
if (cell.answer4.tag==btn.tag)
{
NSLog(#"%ld",(long)btn.tag);
[cell.answer4 setImage:[UIImage imageNamed:#"RadioChecked"] forState:UIControlStateNormal];
}else{
[cell.answer4 setImage:[UIImage imageNamed:#"RadioUnChecked"] forState:UIControlStateNormal];
}
}
You need add one key your datasource array and modify that key value depend upon button state on click action. Check below code for your reference
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
MyCustomTableViewCell *cell = (MyCustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:#"MyCustomTableViewCell"];
[cell.btnSelect addTarget:self action:#selector(btnSelectClick:) forControlEvents:UIControlEventTouchUpInside];
cell.btnSelect.selected = [[[self.arraySource objectAtIndex:indexPath.row] valueForKey:#"isSleected"] boolValue];
cell.btnSelect.tag = indexPath.row;
return cell;
}
- (void)btnSelectClick:(UIButton *)sender {
sender.selected = !sender.selected;
NSMutableDictionary *dicTemp = [NSMutableDictionary dictionaryWithDictionary:[self.arraySource objectAtIndex:sender.tag]];
[dicTemp setValue:[NSNumber numberWithBool:sender.selected] forKey:#"isSleected"];
[self.arraySource replaceObjectAtIndex:sender.tag withObject:dicTemp];
}
Here is arraySource in view did load
self.arraySource = [NSMutableArray array];
[self.arraySource addObject:#{#"name":#"name-1"}];
[self.arraySource addObject:#{#"name":#"name-2"}];
[self.arraySource addObject:#{#"name":#"name-3"}];
I have two UIButtons on each UITableViewCell and I'm basically trying to set both of the buttons to hide when one or the other is pressed. The only thing I found online are just about using .tag to record a press.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * indentifer = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indentifer forIndexPath:indexPath];
// Configure the cell...
cell.textLabel.text = [self.random objectAtIndex:indexPath.row];
UIButton * acecept = [UIButton buttonWithType:UIButtonTypeRoundedRect];
acecept.frame = CGRectMake(cell.bounds.origin.x + 200, cell.bounds.origin.y + 20 , 50, 30);
[acecept setTitle: #"Yes" forState:UIControlStateNormal];
[acecept addTarget:self action:#selector(waffles:) forControlEvents:UIControlEventTouchUpInside];
acecept.backgroundColor = [UIColor whiteColor];
[cell.contentView addSubview:acecept];
self.deny = [UIButton buttonWithType:UIButtonTypeRoundedRect];
_deny.frame = CGRectMake(cell.bounds.origin.x + 250, cell.bounds.origin.y + 20 , 50, 30);
[_deny setTitle: #"no" forState:UIControlStateNormal];
[_deny addTarget:self action:#selector(cereal:) forControlEvents:UIControlEventTouchUpInside];
_deny.backgroundColor = [UIColor whiteColor];
[cell.contentView addSubview:_deny];
UIButton * button = (UIButton *) acecept;
button.tag = button.tag+1;
/* if (acecept.hidden) {
[_deny setHidden:YES];
} */
return cell;
}
This is how I'm hiding them once they are pressed:
-(IBAction) waffles:(id)sender {
NSLog(#"waffles");
UIButton * button = (UIButton *) sender;
button.tag = button.tag+1;
NSLog(#"%ld", (long)button.tag);
waff = button.tag;
[sender setHidden:YES];
if(sender.hidden == YES){
[self.deny setHidden:YES];
}
}
-(IBAction)cereal:(id)sender{
NSLog(#"cereal");
[sender setHidden:YES];
}
I've tried multiple if statements and tagging the button. I think I need to somehow get the number of the cell view at which one of the button is pressed at, then place that in each IBAction.
I have made changes in your code..
Check below code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString * indentifer = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indentifer forIndexPath:indexPath];
// Configure the cell...
cell.textLabel.text = [self.random objectAtIndex:indexPath.row];
UIButton * acecept = [UIButton buttonWithType:UIButtonTypeRoundedRect];
acecept.frame = CGRectMake(cell.bounds.origin.x + 200, cell.bounds.origin.y + 20 , 50, 30);
[acecept setTitle: #"Yes" forState:UIControlStateNormal];
[acecept addTarget:self action:#selector(waffles:) forControlEvents:UIControlEventTouchUpInside];
acecept.backgroundColor = [UIColor whiteColor];
acecept.tag = 1;
[cell.contentView addSubview:acecept];
UIButton * deny = [UIButton buttonWithType:UIButtonTypeRoundedRect];
deny.frame = CGRectMake(cell.bounds.origin.x + 250, cell.bounds.origin.y + 20 , 50, 30);
[deny setTitle: #"no" forState:UIControlStateNormal];
[deny addTarget:self action:#selector(cereal:) forControlEvents:UIControlEventTouchUpInside];
deny.backgroundColor = [UIColor whiteColor];
deny.tag = 2;
[cell.contentView addSubview:_deny];
return cell;
}
-(IBAction) waffles:(id)sender {
NSLog(#"waffles");
UIButton *aceceptBtn = (UIButton *) sender;
[aceceptBtn setHidden:YES];
UIButton *denyBtn = [aceceptBtn.superview viewWithTag:2];
[denyBtn setHidden:YES];
}
-(IBAction)cereal:(id)sender{
NSLog(#"cereal");
UIButton *denyBtn = (UIButton *) sender;
[denyBtn setHidden:YES];
UIButton *aceceptBtn = [denyBtn.superview viewWithTag:1];
[aceceptBtn setHidden:YES];
}
The approach that you are using is not right.
You need to create a custom tableview cell with two buttons.
And in that cell's .m class, you can write IBActions for those two buttons.
And in those IBActions, you can hide both the buttons.
In .h declares buttons in this way (with an Outlet)
#property (weak, nonatomic) IBOutlet UIButton *buttonOne;
#property (weak, nonatomic) IBOutlet UIButton *buttonTwo;
In .m:
-(IBAction)presentPrincipalViewController:(id)sender {
[self.buttonOne setHidden:YES];
[self.buttonTwo setHidden:YES];
}
if you want to hide all buttons:
-(IBAction)presentPrincipalViewController:(id)sender {
for (UIButton* someButton in self.view.subviews) {
[someButton setHidden:YES];
}
}
I am having a list displaying a name and a button titled as "Follow". When I tap on the button title should change to "UnFollow". If I tap on the button again the title should again change to "Follow". This is working fine, but when I am scrolling the table the title of the other cells are also changing due to cell reuse.
The code is as follows:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"AuthorsListCell";
AuthorsListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier
forIndexPath:indexPath];
dic_eachAuthor = [[_arr_authors objectAtIndex:indexPath.row] mutableCopy];
cell.lbl_authorName.text = [dic_eachAuthor objectForKey:#"name"];
cell.btn_followOrUnfollow.tag = indexPath.row;
if([dic_eachAuthor valueForKey:#"follow"]){
[cell.btn_followOrUnfollow setTitle:#"UnFollow" forState:UIControlStateNormal];
}
else{
[cell.btn_followOrUnfollow setTitle:#"Follow" forState:UIControlStateNormal];
}
// action button method declarations
[cell.btn_followOrUnfollow addTarget:self action:#selector(followOrUnfollow:) forControlEvents:UIControlEventTouchUpInside];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
-(void)followOrUnfollow:(UIButton *)sender
{
if ([sender.titleLabel.text isEqualToString:#"Follow"]) {
[sender setTitle:#"UnFollow" forState:UIControlStateNormal];
[dic_eachAuthor setValue:#"1" forKey:#"follow"];
}
else if ([sender.titleLabel.text isEqualToString:#"UnFollow"]) {
[sender setTitle:#"Follow" forState:UIControlStateNormal];
[dic_eachAuthor setValue:nil forKey:#"follow"];
}
}
Please suggest something to prevent the cell reuse.
Add this condition in followOrUnfollow in cellForRowAtIndexPath also
if ([sender.titleLabel.text isEqualToString:#"Follow"]) {
[sender setTitle:#"UnFollow" forState:UIControlStateNormal];
}
else if ([sender.titleLabel.text isEqualToString:#"UnFollow"]) {
[sender setTitle:#"Follow" forState:UIControlStateNormal];
}
Store follow/unfollow state information within datasource.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"CellIdentifier";
ListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier
forIndexPath:indexPath];
cell.lbl_authorName.text = [[_arr_authors objectAtIndex:indexPath.row] objectForKey:#"name"];
cell.btn_followOrUnfollow.tag = indexPath.row;
// action button method declarations
[cell.btn_followOrUnfollow addTarget:self action:#selector(followOrUnfollow:) forControlEvents:UIControlEventTouchUpInside];
NSString *btnTitle = [[_arr_authors objectAtIndex:indexPath.row] objectForKey:#"userFollowUnfollow"];
[sender setTitle:btnTitle forState:UIControlStateNormal];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
-(void)followOrUnfollow:(UIButton *)sender
{
if ([sender.titleLabel.text isEqualToString:#"Follow"]) {
[sender setTitle:#"UnFollow" forState:UIControlStateNormal];
}
else if ([sender.titleLabel.text isEqualToString:#"UnFollow"]) {
[sender setTitle:#"Follow" forState:UIControlStateNormal];
}
[[_arr_authors objectAtIndex:sender.tag] setValue:sender.titleLabel.text forKey:#"userFollowUnfollow"];
}
When you originally populate the table row, you do it from an array here cell.lbl_authorName.text = [[_arr_authors objectAtIndex:indexPath.row] objectForKey:#"name"];. The problem is that you don't populate the follow or unfollow information from this array. So all you are doing is toggling a button and there is no saving of the state of that button. What you need to do is modify the array to have a place to save the follow/unfollow state. Then populate the state in the table cell from this array. Then when you call followOrUnfollow: you need to modify the state in the array.
When the cell gets reused it goes and checks with the original array to populate it, populate the follow from the array and you will be set.
Edited to add some code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"CellIdentifier";
ListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.lbl_authorName.text = [[_arr_authors objectAtIndex:indexPath.row] objectForKey:#"name"];
cell.btn_followOrUnfollow.tag = indexPath.row;
if([[_arr_authors objectAtIndex:indexPath.row] valueForKey:#"follow"]){
[cell.btn_followOrUnfollow setTitle:#"UnFollow" forState:UIControlStateNormal];
else{
[cell.btn_followOrUnfollow setTitle:#"Follow" forState:UIControlStateNormal];
}
// action button method declarations
[cell.btn_followOrUnfollow addTarget:self action:#selector(followOrUnfollow:) forControlEvents:UIControlEventTouchUpInside];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
-(void)followOrUnfollow:(UIButton *)sender
{
if ([sender.titleLabel.text isEqualToString:#"Follow"]) {
[sender setTitle:#"UnFollow" forState:UIControlStateNormal];
[[_arr_authors objectAtIndex:sender.tag] setValue:1 forKey:#"follow"]
}
else if ([sender.titleLabel.text isEqualToString:#"UnFollow"]) {
[sender setTitle:#"Follow" forState:UIControlStateNormal];
[[_arr_authors objectAtIndex:sender.tag] setValue:0 forKey:#"follow"]
}
}
I am not at my normal machine, so the syntax is probably off, but you should get the idea. Also note you will have to add the follow property to _arr_authors
You are missing something here, try this :
-(void)followOrUnfollow:(UIButton *)sender
{
NSDictionary *dict = (NSDictionary *) _arr_authors[sender tag];
if ([[dict objectForKey:#"name"] isEqualToString:#"Follow"])
{
[sender setTitle:#"UnFollow" forState:UIControlStateNormal];
}
else if ([[dict objectForKey:#"name"] isEqualToString:#"UnFollow"])
{
[sender setTitle:#"Follow" forState:UIControlStateNormal];
}
}
You are cells are reused so please implement this method in AuthorsListTableViewCell:
-(void) prepareForReuse{
[super prepareForReuse];
[self.btn_followOrUnfollow setTitle:#"Follow" forState:UIControlStateNormal];
}
// if the cell is reusable (has a reuse identifier), this is called just before the cell is returned from the table view method dequeueReusableCellWithIdentifier:. If you override, you MUST call super.
And set the correct default value to the cell.
I also recommend to implement this way:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"AuthorsListCell";
AuthorsListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier
forIndexPath:indexPath];
cell.lbl_authorName.text = [dic_eachAuthor objectForKey:#"name"];
cell.btn_followOrUnfollow.tag = indexPath.row;
[cell.btn_followOrUnfollow setTitle:#"Follow forState:UIControlStateNormal];
[cell.btn_followOrUnfollow setTitle:#"UnFollow" forState:UIControlStateSelected];
if([dic_eachAuthor valueForKey:#"follow"]){
cell.btn_followOrUnfollow.selected = YES;
} else{
cell.btn_followorUnfollow.selected = NO;
}
// action button method declarations
[cell.btn_followOrUnfollow addTarget:self action:#selector(followOrUnfollow:) forControlEvents:UIControlEventTouchUpInside];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
-(void)followOrUnfollow:(UIButton *)sender
{
sender.selected = !sender.selected;
if ([sender.titleLabel.text isEqualToString:#"Follow"]) {
[dic_eachAuthor setValue:#"1" forKey:#"follow"];
}
else if ([sender.titleLabel.text isEqualToString:#"UnFollow"]) {
[dic_eachAuthor setValue:nil forKey:#"follow"];
}
}
In AuthorsListTableViewCell
-(void) prepareForReuse{
[super prepareForReuse];
self.btn_followOrUnfollow.selected = NO;
}
Possible duplicates :
how to change tableView Cell button on click in iphone
I have button in table view cell with background images set using this function.
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
SectionsTableIdentifier];
cell.textLabel.text = self.names[self.keys];
if (cell.accessoryView == nil) {
UIImage *buttonUpImage = [UIImage imageNamed:#"button_up.png"];
UIImage *buttonDownImage = [UIImage imageNamed:#"button_down.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage:buttonUpImage
forState:UIControlStateNormal];
[button setBackgroundImage:buttonDownImage
forState:UIControlStateHighlighted];
[button setTitle:#"Send" forState:UIControlStateNormal];
[button sizeToFit];
[button addTarget:self
action:#selector(tappedButton:)
forControlEvents:UIControlEventTouchUpInside];
cell.accessoryView = button;
}
return cell;
}
Code for Tapped Button is :
- (void)tappedButton:(UIButton *)sender
{
NSInteger row = sender.tag;
// NSString *character = self.names[self.keys];
/* NSString *key = self.keys[indexPath.row];
NSArray *nameSection = self.names[key];
NSString *character = nameSection[indexPath];
*/
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Request Notification."
message:[NSString
stringWithFormat:#"Friend Request Sent ."]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
/* UIImage *buttonUpImage = [UIImage imageNamed:#"button.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[cell.theSyncButton setImage:buttonUpImage forState:UIControlStateSelected];
[button setBackgroundImage:buttonUpImage
forState:UIControlStateNormal];
[button setTitle:#"Sent" forState:UIControlStateNormal];
[button sizeToFit];
*/
}
Now i require is to change background color and title to "sent" dynamically when user click on "Send" button in table view cell .How i can get this functionality ?
Try this,
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
....
UIButton *button;
if (cell.accessoryView == nil) {
...
button = [UIButton buttonWithType:UIButtonTypeCustom];
....
cell.accessoryView = button;
}
button.tag = indexPath.row;
...
}
in tappedButton:
- (void)tappedButton:(UIButton *)sender
{
NSInteger row = sender.tag;
UIImage *buttonUpImage = [UIImage imageNamed:#"button.png"];
[sender setBackgroundImage:buttonUpImage
forState:UIControlStateNormal];
[sender setTitle:#"Sent" forState:UIControlStateNormal];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];
}
Hi you can do following,
- (void)tappedButton:(UIButton *)sender
{
[sender setBackgroundColor:[UIColor grayColor]];
[sender setTitle:#"Sent" forState:UIControlStateNormal];
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Request Notification."
message:[NSString
stringWithFormat:#"Friend Request Sent ."]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
In your IBAction method tappedButton you get passed the button that the user tapped (the "sender" parameter.)
Change the background color and title of "sender"
[sender setBackgroundColor:[UIColor whiteColor]];
((UIButton *)sender).titleLabel.text = #"title";
Use selected state of button, in
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
[button setTitle:#"Send" forState:UIControlStateNormal];
[button setBackgroundImage:original_image forState:UIControlStateNormal];
[button setTitle:#"Sent" forState:UIControlStateSelected];
[button setBackgroundImage:selected_image forState:UIControlStateSelected];
}
In tappedButton() function set sender to selected using [sender setSelected:YES]
The main reason for this approch is you can detect state of button using isSelected method.