selected accessoryView for specified cells - ios

the question is quite simple. How can you make an accessoryView in a tableView to be "Selected" for each row that has the same title in both section 0 and 1? (iOS)
I want to do this because when I select the accessoryView in a row, the row copies up to a new section 0 which is called "favorites". But the problem is, if I deselect the row in section 0, the row disappears but the accessoryView stays selected for the corresponding row in section 1, which I wan't to be deselected in that case. Thanks in advance.
-(void)addToFavs:(id)sender event:(id)event {
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
UIButton *button = (UIButton*)sender;
if(indexPath!=nil){
if(button.selected==YES){
button.selected = NO;
}else{
button.selected =YES;
}
[self tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//cell
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell){
// left image
UIImageView *image=[[UIImageView alloc] initWithFrame:CGRectMake(7, 7, 30, 30)];
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.detailTextLabel.textColor=[UIColor lightGrayColor];
cell.textLabel.text=self.objects[indexPath.row];
cell.detailTextLabel.text =self.subtitles[indexPath.row];
[cell.contentView addSubview:image];
if(indexPath.section==0){
image.image=[UIImage imageNamed:[self.iconsFavs objectAtIndex:indexPath.row]];
cell.textLabel.text=self.favs[indexPath.row];
cell.detailTextLabel.text =self.subtitlesFavs[indexPath.row];
}else{
image.image=[UIImage imageNamed:[self.icons objectAtIndex:indexPath.row]];
}
//favorites image button
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect frame = CGRectMake(0.0, 0.0, 25, 25);
button.frame = frame;
button.showsTouchWhenHighlighted = YES;
[button setImage:[UIImage imageNamed:#"unfavorites.png"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:#"favorites.png"] forState:UIControlStateSelected];
[button addTarget:self action:#selector(addToFavs:event:) forControlEvents:UIControlEventTouchUpInside];
if(indexPath.section==0){
button.selected = !button.selected;
}
cell.accessoryView.tag=indexPath.row;
button.backgroundColor = [UIColor clearColor];
cell.accessoryView = button;
}
return cell;
}

Easy way to do this, create an array for favorite and add item to this array on select. And select accessory view if the item is in array of favorites.

Related

UiButton text wont stay changed in Tableview cell

I have searched all over the web and cant seem to find a solution to this simple problem. I have a table view of buttons when the work "like". When the Button is pressed, it changes the word to "Unlike". I got it to work but when I scroll down the table, I see other buttosn also change to "unlike" and sometimes overlaps it with "Like". And when I scroll back up, the original button I selected changes back to normal state. I understand the cells are reusable and thats why I am using a mutable array for my data source and still it doesnt work. Please help!
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[myButton setTitle:#"Like" forState:UIControlStateNormal];
myButton addTarget:self action:#selector(tapped:) forControlEvents:UIControlEventTouchUpInside];
myButton.frame = CGRectMake(14.0, 10.0, 125.0, 25.0);
myButton.tag =indexPath.row;
[cell.contentView addSubview:myButton];
cell.textLabel.text = [recipes objectAtIndex:indexPath.row];
return cell;
}
the action method:
-(void)tapped:(id)sender {
UIButton *senderButton = (UIButton *)sender;
UITableViewCell *parentCell = [[sender superview]superview];
NSIndexPath *indexPathLiked = [table indexPathForCell:parentCell];
[array replaceObjectAtIndex:senderButton.tag withObject:[NSNumber numberWithInt:1]];
[sender setTitle:#"Unlike" forState:UIControlStateNormal];
}
If the table calls the cellForRowAtIndexPath you create all the time a new button. When you get a reused cell the button still exists and you put a new one over there.
Change your method to:
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[myButton setTitle:#"Like" forState:UIControlStateNormal];
myButton addTarget:self action:#selector(tapped:) forControlEvents:UIControlEventTouchUpInside];
myButton.frame = CGRectMake(14.0, 10.0, 125.0, 25.0);
myButton.tag =indexPath.row;
[cell.contentView addSubview:myButton];
}
else {
// todo: change the button title to "like" or "unliked" value
}
cell.textLabel.text = [recipes objectAtIndex:indexPath.row];
P.S. This make no sense, you doesn't use that, why you do that?
UITableViewCell *parentCell = [[sender superview]superview];
NSIndexPath *indexPathLiked = [table indexPathForCell:parentCell];
If you have only one section you can get the cell without using superview:
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag inSection:0]
UITableViewCell *parentCell = [table cellForRowAtIndexPath:indexPath];

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.

tableView adding/removing to second section objective-c

I have two sections in my tableview(iOS), where the first one is for the "favorites" rows. If you select the accessoryView it should add/remove the selected object in the "objects" array to/from "favs" array depending if the object already exist in the section.
The method I wrote almost works, but when I add a second row, or the same to remove it in favorites, the app crashes with this error:
Terminating app due to uncaught exception NSRangeException', reason: *** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]
The problem is that the index of the object in the corresponding arrays is not the same so I can't really figure out how to make this work properly.
Here's some code:
-(void)addToFavs:(id)sender{
UITapGestureRecognizer *gesture = (UITapGestureRecognizer *) sender;
NSLog(#"Tag = %d", gesture.view.tag);
//if favorite section is empty
if ([self.favs isEqualToArray:[#[]mutableCopy]]) {
NSLog(#"adding favorite");
[self.favs addObject:[self.objects objectAtIndex:gesture.view.tag]];
[self.subtitlesFavs addObject:[self.subtitles objectAtIndex:gesture.view.tag]];
[self.iconsFavs addObject:[self.icons objectAtIndex:gesture.view.tag]];
}
//if selected row already exist in favorites array <--HERE IS THE PROBLEM (I THINK)
else if([[self.objects objectAtIndex:gesture.view.tag] isEqualToString:[self.favs objectAtIndex:gesture.view.tag]]){
NSLog(#"removing favorite");
[self.favs removeObjectAtIndex:gesture.view.tag];
[self.subtitlesFavs removeObjectAtIndex:gesture.view.tag];
[self.iconsFavs removeObjectAtIndex:gesture.view.tag];
}else{
NSLog(#"adding favorite");
[self.favs addObject:[self.objects objectAtIndex:gesture.view.tag]];
[self.subtitlesFavs addObject:[self.subtitles objectAtIndex:gesture.view.tag]];
[self.iconsFavs addObject:[self.icons objectAtIndex:gesture.view.tag]];
}
[self.tableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// left image
UIImageView *image=[[UIImageView alloc] initWithFrame:CGRectMake(7, 7, 30, 30)];
[image.layer setCornerRadius:image.frame.size.width/2];
[image setClipsToBounds:YES];
if(indexPath.section==0){
image.image=[UIImage imageNamed:[self.iconsFavs objectAtIndex:indexPath.row]];
}else{
image.image=[UIImage imageNamed:[self.icons objectAtIndex:indexPath.row]];
}
//fav image
UIImageView *fav = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"favorites.png"]];
[fav setFrame:CGRectMake(0, 0, 25, 25)];
[fav setClipsToBounds:YES];
if(!indexPath.section==0) {
fav.image=[UIImage imageNamed:#"unfavorites"];
}
//cell
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell){
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.text=self.objects[indexPath.row];
cell.detailTextLabel.text =self.subtitles[indexPath.row];
[cell.contentView addSubview:image];
cell.accessoryView = fav;
//Favorites
cell.accessoryView.userInteractionEnabled = YES;
cell.accessoryView.tag = indexPath.row;
UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(addToFavs:)];
tapped.numberOfTapsRequired = 1;
[cell.accessoryView addGestureRecognizer:tapped];
//favorites section contents
if (indexPath.section == 0)
{
cell.textLabel.text=self.favs[indexPath.row];
[cell.contentView addSubview:image];
cell.detailTextLabel.text =self.subtitlesFavs[indexPath.row];
}
}
return cell;
}
Update 1
I edited my code with "isEqualToString" in the if-condition but it still doesn't work to remove them...
Quite similar to what you have but try this anyways:
this be the -cellForRowAtIndexPath: method --
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier];
}
cell.detailTextLabel.textColor = [UIColor lightGrayColor];
//following commented line not needed
//cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
// left image
UIImageView *image = [[UIImageView alloc] init];
[image setFrame:CGRectMake(7, 7, 30, 30)];
[image.layer setCornerRadius:image.frame.size.width/2];
[image setClipsToBounds:YES];
[image.layer setBorderColor:[UIColor lightGrayColor].CGColor];
[image.layer setBorderWidth:0.3f];
[cell.contentView addSubview:image];
//favorites image button
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(0, 0, 25, 25)];
[button setBackgroundColor:[UIColor clearColor]];
[button setImage:[UIImage imageNamed:#"unfavorites.png"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:#"favorites.png"] forState:UIControlStateSelected];
[button setTag:100]; //tag needed later
[button addTarget:self action:#selector(addToFavs:event:) forControlEvents:UIControlEventTouchUpInside];
[button setShowsTouchWhenHighlighted:YES];
[cell setAccessoryView:button];
switch(indexPath.section) {
case 0: { //is first section (favourite)
image.image = [UIImage imageNamed: self.iconsFavs[indexPath.row]];
cell.textLabel.text = self.favs[indexPath.row];
cell.detailTextLabel.text = self.subtitlesFavs[indexPath.row];
[button setSelected:YES];
}
break;
case 1: { //is second section (all clubs)
image.image = [UIImage imageNamed: self.icons[indexPath.row]];
cell.textLabel.text = self.objects[indexPath.row];
cell.detailTextLabel.text = self.subtitles[indexPath.row];
//change state of button (thereby change button image)
if([self.favs containsObject: self.objects[indexPath.row]]) {
[button setSelected:YES];
} else {
[button setSelected:NO];
}
}
break;
}
//separator -- do the following on viewDidLoad instead
//[self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 45, 0, 0)];
return cell;
}
this be the -addToFavs:event: method --
//No need for `-accessoryButtonTappedForRowWithIndexPath:` method
//it can be done in your following `-addToFavs:event:` method alone:
-(void)addToFavs:(id)sender event:(id)event
{
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:currentTouchPosition];
switch(indexPath.section) {
case 0: { //is first section (favourite)
//remove from favourites
//get indexPath for appropraite row in second section
NSUInteger i_indexOfFavInMain = [self.objects indexOfObject:self.favs [indexPath.row]];
NSIndexPath *indexOfFavInMain = [NSIndexPath indexPathForItem:i_indexOfFavInMain inSection:1];
[self.favs removeObjectAtIndex:indexPath.row];
[self.subtitlesFavs removeObjectAtIndex:indexPath.row];
[self.iconsFavs removeObjectAtIndex:indexPath.row];
//handle second section button (for the appropriate row)
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexOfFavInMain];
UIButton *btnTemp = (UIButton *)[cell viewWithTag:100];
[btnTemp setSelected:NO];
//reload first section
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
}
break;
case 1: { //is second section (all clubs)
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
UIButton *btnTemp = (UIButton *)[cell viewWithTag:100];
if([self.favs containsObject:self.objects[indexPath.row]]) {
//remove from favourites
[self.favs removeObject:self.objects[indexPath.row]];
[self.subtitlesFavs removeObject:self.subtitles[indexPath.row]];
[self.iconsFavs removeObject:self.icons[indexPath.row]];
[btnTemp setSelected:NO];
} else {
//add to favourites
[self.favs addObject: self.objects[indexPath.row]];
[self.subtitlesFavs addObject: self.subtitles[indexPath.row]];
[self.iconsFavs addObject: self.icons[indexPath.row]];
[btnTemp setSelected:YES];
}
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
}
break;
}
}
Here's the solution. Moving everything to accessoryButoonTappedForRowWithIndexPath and having four different cases did the trick. Also make sure to not have strings that are the same in the arrays otherwise it will remove all of them and you will get an index error.
-(void)addToFavs:(id)sender event:(id)event {
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
if(indexPath!=nil){
[self tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
}
}
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
if ([self.favs count]==0) {
NSLog(#"adding first favorite %#",[self.objects objectAtIndex:indexPath.row]);
[self.favs addObject:[self.objects objectAtIndex:indexPath.row]];
[self.subtitlesFavs addObject:[self.subtitles objectAtIndex:indexPath.row]];
[self.iconsFavs addObject:[self.icons objectAtIndex:indexPath.row]];
}else if (indexPath.section==0){
NSLog(#"removing favorite %#",[self.favs objectAtIndex:indexPath.row]);
[self.favs removeObjectAtIndex:indexPath.row];
[self.subtitlesFavs removeObjectAtIndex:indexPath.row];
[self.iconsFavs removeObjectAtIndex:indexPath.row];
}else if(indexPath.section==1 && [self.favs containsObject:[self.objects objectAtIndex:indexPath.row]]){
NSLog(#"removing favorite %#",[self.objects objectAtIndex:indexPath.row]);
[self.favs removeObject:[self.objects objectAtIndex:indexPath.row]];
[self.subtitlesFavs removeObject:[self.subtitles objectAtIndex:indexPath.row]];
[self.iconsFavs removeObject:[self.icons objectAtIndex:indexPath.row]];
}else{
NSLog(#"adding favorite %#",[self.objects objectAtIndex:indexPath.row]);
[self.favs addObject:[self.objects objectAtIndex:indexPath.row]];
[self.subtitlesFavs addObject:[self.subtitles objectAtIndex:indexPath.row]];
[self.iconsFavs addObject:[self.icons objectAtIndex:indexPath.row]];
}
[tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//cell
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell){
// left image
UIImageView *image=[[UIImageView alloc] initWithFrame:CGRectMake(7, 7, 30, 30)];
[image.layer setCornerRadius:image.frame.size.width/2];
[image setClipsToBounds:YES];
[image.layer setBorderColor:[UIColor lightGrayColor].CGColor];
[image.layer setBorderWidth:0.3f];
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.detailTextLabel.textColor=[UIColor lightGrayColor];
cell.textLabel.text=self.objects[indexPath.row];
cell.detailTextLabel.text =self.subtitles[indexPath.row];
[cell.contentView addSubview:image];
if(indexPath.section==0){
image.image=[UIImage imageNamed:[self.iconsFavs objectAtIndex:indexPath.row]];
cell.textLabel.text=self.favs[indexPath.row];
cell.detailTextLabel.text =self.subtitlesFavs[indexPath.row];
}else{
image.image=[UIImage imageNamed:[self.icons objectAtIndex:indexPath.row]];
}
//separetor
[self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 45, 0, 0)];
//favorites image button
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect frame = CGRectMake(0.0, 0.0, 25, 25);
button.frame = frame;
button.showsTouchWhenHighlighted = YES;
[button setImage:[UIImage imageNamed:#"unfavorites.png"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:#"favorites.png"] forState:UIControlStateSelected];
[button addTarget:self action:#selector(addToFavs:event:) forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor = [UIColor clearColor];
cell.accessoryView = button;
}
return cell;
}

Actions on the buttons of the cell

In UITableViewCell there are different buttons on different cells and when I click on the button of the cell the same action is being performed on all the cell's button, but I want that when I press the button of particular cell then the action of that cell should work, I know I need to put them in array, but how?
when I click on the button one value is being incremented and it should be shown on the label of the same cell.
here is the 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];
}
SHEDLIST *info1 = [shed_list objectAtIndex:indexPath.row];
cell.textLabel.text=info1.SHED_Name;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
IDlbl = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 50, 50)];
IDlbl.text = info1.SHED_ID;
IDlbl.textAlignment = NSTextAlignmentCenter;
[cell addSubview:IDlbl];
tickbtn = [UIButton buttonWithType:UIButtonTypeCustom];
[tickbtn setBackgroundImage:[UIImage imageNamed:#"tick.png"]forState:UIControlStateNormal];
[tickbtn addTarget:self action:#selector(addsheddata) forControlEvents:UIControlEventTouchUpInside];
tickbtn.frame = CGRectMake(170, 5, 30, 30);
[cell addSubview:tickbtn];
return cell;
}
-(void) addsheddata:(UIEvent *)event
{
// here i am performing my action which i want.
}
First assign tag to your button.
[tickbtn setTag:indexPath.row];
[tickbtn addTarget:self action:#selector(addsheddata:) forControlEvents:UIControlEventTouchUpInside];
tickbtn.frame = CGRectMake(170, 5, 30, 30);
[cell addSubview:tickbtn];
Correct your method implementation by this.
-(IBAction) addsheddata:(UIControl *)sender
{
// here i am performing my action which i want.
UIButton *button = (UIButton*)sender;
NSIndexPath *myIP = [NSIndexPath indexPathForRow:sender.tag inSection:0];
//Type cast cell
UITableViewCell *cell = (UITableViewCell*)[mytblView cellForRowAtIndexPath:myIP];
UILabel *lbl = cell.lbl;
lbl.text = #"Your text";
}
Add target like this to your button
[tickbtn addTarget:self action:#selector(addsheddata:event:) forControlEvents:UIControlEventTouchUpInside];
And method should be like this:
- (void) addsheddata:(id)sender event:(id)event {
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:chatContent];
NSIndexPath *indexPath = [YOUR_TABLE_OBJ indexPathForRowAtPoint: currentTouchPosition];
UITableViewCell *cell = [YOUR_TABLE_OBJ cellForRowAtIndexPath:indexPath];
}
tickbtn = [UIButton buttonWithType:UIButtonTypeCustom];
[tickbtn setBackgroundImage:[UIImage imageNamed:#"tick.png"]forState:UIControlStateNormal];
[tickbtn addTarget:self action:#selector(addsheddata) forControlEvents:UIControlEventTouchUpInside];
tickbtn.frame = CGRectMake(170, 5, 30, 30);
[cell addSubview:tickbtn];
NSString *str=[urarray objectAtIndex:indexPath.row];
[tickbtn setTag:[str intValue]];
-(void) addsheddata:(UIEvent *)event
{
UITableViewCell *clickedCell = (UITableViewCell *)[sender superview] ;
NSIndexPath *clickedButtonPath = [urtableview indexPathForCell:clickedCell];
}
At cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
tickbtn.tag =500+indexPath.row;
//Initialise your UILabel *lbl and define
lbl.tag = 200+indexPath.row;
lbl.text = // Add Text
// Add the Uilabel to the tableView
}
Action by handling the tag
-(IBAction) addsheddata:(UIButton *)sender{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag-500 inSection:0];
UILabel *lbl = (UILabel *)[self.view viewWithTag:indexPath.Row+200];
NSLog (#"%#", lbl.text);
// Do further as per your Requirement
}

Detect which button was clicked in a grouped UITableView

I have a grouped UITableView (this one has 4 sections) and several rows each. I have programatically created 2 buttons in each of the cells.
This is how I am creating the UITableViewCell. In this code, I am trying to detect the indexPath.row and the indexPath.section of the button that was pressed and pass it to the method. How am I able to do this ?
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellId = #"Cell";
UITableViewCell *cell ;//= [tableView dequeueReusableCellWithIdentifier:nil];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
}
NSString *docTitle = [currentDocument objectForKey:#"displayname"];
UIView *cellView = [[UIView alloc] initWithFrame:CGRectMake(cell.contentView.frame.origin.x+5, cell.contentView.frame.origin.y, cell.contentView.frame.size.width, cell.contentView.frame.size.height)];
UILabel *cellTitle = [[UILabel alloc] initWithFrame:CGRectMake(cellView.frame.origin.x + 5, cellView.frame.origin.y + 5, cellView.frame.size.width - 10, 25)];
cellTitle.backgroundColor = [UIColor clearColor];
cellTitle.text = docTitle;
[cellView addSubview:cellTitle];
[cell.contentView addSubview:cellView];
UIButton *viewDocumentButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[viewDocumentButton setTitle:#"View Online" forState:UIControlStateNormal];
viewDocumentButton.frame = CGRectMake(cellView.frame.origin.x + 5, cellTitle.frame.origin.y + cellTitle.frame.size.height + 5, 150, 35);
[viewDocumentButton addTarget:self action:#selector(openDocumentButtonPressedMethod:) forControlEvents:UIControlEventTouchDown];
[viewDocumentButton setTag:indexPath.row];
[cell.contentView addSubview:viewDocumentButton];
UIButton *downloadDocumentButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[downloadDocumentButton setTitle:#"Download Document" forState:UIControlStateNormal];
downloadDocumentButton.frame = CGRectMake(cellView.frame.origin.x + 5, viewDocumentButton.frame.origin.y + viewDocumentButton.frame.size.height + 5, 150, 35);
[downloadDocumentButton addTarget:self action:#selector(openDocumentButtonPressedMethod:) forControlEvents:UIControlEventTouchDown];
[downloadDocumentButton setTag:indexPath.row];
[cell.contentView addSubview:downloadDocumentButton];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
Additionally, you could...
- (IBAction)openDocumentButtonPressedMethod:(id)sender {
UIButton *button = (UIButton *)sender;
UIView *contentView = button.superview;
UITableViewCell *cell = (UITableViewCell *)contentView.superview;
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
// do something with the indexPath
}
And if you wanted to use the same method to handle both button events, then you could use the tag on the button to distinguish between the two buttons.
if (button.tag == 1) {
// do something with the indexPath view related
}
else {
// do something with the indexPath download related
}
Create a subclass of UIButton
#interface MyButton : UIButton
{ /* indexPath, other stuff */ }
#end
Then implement
- (void)sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event
to do something with the indexPath and other stuff before invoking the super for this method.
When you create the button, provide indexPath.
In your openDocumentButtonPressedMethod: method, do
CGPoint pointInTableView = [self.tableView convertPoint:sender.bounds.origin fromView:sender];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:pointInTableView];

Resources