Perform animations on custom UITableViewCell - ios

I'm trying to animate a few items in a custom UITableViewCell when a user presses a button in the cell. I have set addTarget: and added a method to animate the items in the cell. I've set a tag for the button so I can get the index. In the method, I call cellForRowAtIndexPath: to get the cell the button was called on. I'm casting the object returned by cellForRowAtIndexPath: to my custom cell. After I have the custom cell, I perform the animations on the objects. The problem is the animations aren't happening. When I try setting a property on one of the items in the cell, it doesn't work either. The custom cell is not returning nil so I'm not sure of the issue. What am I doing wrong?
Here is the code I'm using to call the animations
-(void)favButtonPressed:(id)sender{
FavoritesCell *favCell = (FavoritesCell *)[self tableView:self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:[sender tag] inSection:0]];
[UIView animateWithDuration:0.2 animations:^{
favCell.picButton.alpha = 0.5;
} completion:nil];
}

One way u can do it by using custom delegate like below, hope this helps u .
i took an example of your case go through this hope this helps u
in custom cell calss define delegate protocol like below
in FavoritesCell.h
#import <UIKit/UIKit.h>
#class FavoritesCell;
#protocol CellActionDelegate <NSObject>
- (void)doAnimationForCell:(FavoritesCell *)cell forButton:(UIButton *)picButton; //in this u can pass the cell itself
#end
#interface FavoritesCell : UITableViewCell
#property (nonatomic,retain)UIButton *picButton; //i am doing a simple test, say this is your pic button
#property (nonatomic,assign) id<CellActionDelegate>cellDelegate;
#end
and in FavoritesCell.m file
#import "FavoritesCell.h"
#implementation FavoritesCell
#synthesize cellDelegate;
#synthesize picButton = _picButton;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
_picButton = [[UIButton alloc]initWithFrame:CGRectMake(20, 3, 100, 100)];
//set the property // for test
[_picButton addTarget:self action:#selector(favButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[_picButton.layer setCornerRadius:50];
[_picButton.layer setMasksToBounds:YES];
[_picButton.layer setBorderColor:[[UIColor blackColor]CGColor]];
[_picButton.layer setBorderWidth:5];
_picButton.backgroundColor = [UIColor greenColor];
[self.contentView addSubview:_picButton];
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)favButtonPressed:(UIButton *)sender
{
//or you can do the animation hear only no need to delegate to controller form cell
if([self.cellDelegate respondsToSelector:#selector(doAnimationForCell:forButton:)])
{
[self.cellDelegate doAnimationForCell:self forButton:sender]; //call this method
}
}
#end
in ViewController.h file
#import <UIKit/UIKit.h>
#import "FavoritesCell.h" //import it
#interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate,CellActionDelegate> //confirms to delegate
//.... other stuffs
in ViewController.m file
//...other stuffs
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 5;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
FavoritesCell *cell = [tableView dequeueReusableCellWithIdentifier:#"CELL"];
if(cell == nil)
{
cell = [[FavoritesCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"CELL"];
}
cell.cellDelegate = self; //set the deleagte to this class
[cell.picButton setImage:[UIImage imageNamed:#"Two-Red-Flower-.jpg"] forState:UIControlStateNormal]; //set it hear or in custom cell itself
//...other logics
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 130.0f;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
//define the delegate method
- (void)doAnimationForCell:(FavoritesCell *)cell forButton:(UIButton *)picButton //this the picButton
{
//you can get index path of cell
//you can get the tapped button of the cell
//then do your animation
[UIView animateWithDuration:0.2 animations:^{
picButton.alpha = 0.5;
} completion:nil];
}

I think you want something like this:
-(void)favButtonPressed:(id)sender
{
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.myTableView];
// or try this one alternatively if the above line give wrong indexPath
//CGPoint buttonPosition = [sender convertPoint:((UIButton *)sender).center toView:self.myTableView];
NSIndexPath *indexPath = [self.myTableView indexPathForRowAtPoint:buttonPosition];
// I assume "self" here is your view controller
FavoritesCell *favCell = (FavoritesCell *)[self.myTableView cellForRowAtIndexPath:indexPath];
[UIView animateWithDuration:0.2 animations:^{
favCell.picButton.alpha = 0.5;
} completion:nil];
}

Related

How to write action for UIButton which is loaded into tableview as custom cell?

Hi I'm new to iOS Development and i am using Objective C. I have a problem in UITableview.That is, i need to write action for multiple UIButton which is loaded into a tableview(DutiesTableView.m & .h) as a custom cell(BreakTimeCell.m &.h). That tableview(DutiesTableView.m & .h) is loaded into another tableview(ViewController.m&.h, TableName is PersonalTable) as s custom cell using XIB.
[Shift(custom cell),Duties(UITableview),Break Time(UITableview)],[This is my ViewController.m
This is my sample output.When i click on the Break time UIButton it should show UIDatePicker on Main Tableview
Create A button,
UIButton *btnSample = [[UIButton alloc]initWithFrame:CGRectMake(215,10,100,50)];
[btnSample setTitle:#"Button Title" forState:UIControlStateNormal];
[yourView addSubview:btnSample];
Add a action to button
[btnSample addTarget:self action:#selector(your action or method) forControlEvents:UIControlEventTouchUpInside];
You can use delegates to get call back from custom cell to your view controller, for example in the custom cell in your code, BreakTimeCell.h file declare a protocol and add button in BreakTimeCell.xib and give outlet and action to custom cell like below,
#import <UIKit/UIKit.h>
#class BreakTimeCell; //forword declaration
#protocol BreakTimeCellDeleagte<NSObject>
- (void)breakTimeCell:(BreakTimeCell *)cell didTapTheButton:(UIButton *)aButton;
#end
#interface BreakTimeCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UIButton *aButton;
#property (weak, nonatomic) id<BreakTimeCellDeleagte> cellDelegate;//this is important
- (IBAction)myButtonAction:(id)sender;
+ (BreakTimeCell *)getBreakTimeCell; //to get the custom cell
#end
and in BreakTimeCell.h file define action for the button
#import "BreakTimeCell.h"
#implementation BreakTimeCell
+ (BreakTimeCell *)getBreakTimeCell {
NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:#"BreakTimeCell" owner:self options:NULL];
NSEnumerator *nibEnumerator = [nibContents objectEnumerator];
BreakTimeCell *customCell = nil;
NSObject* nibItem = nil;
while ((nibItem = [nibEnumerator nextObject]) != nil) {
if ([nibItem isKindOfClass:[BreakTimeCell class]]) {
customCell = (BreakTimeCell *)nibItem;
break;
}
}
return customCell;
}
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
//call the delegate method in the button action
- (IBAction)myButtonAction:(id)sender {
if([self.cellDelegate respondsToSelector:#selector(breakTimeCell:didTapTheButton:)])
{
[self.cellDelegate breakTimeCell:self didTapTheButton:sender];
}
}
#end
and in view controller just set the cell delegate to view controller,
#import "ViewController.h"
#import "BreakTimeCell.h"
#interface ViewController ()<UITableViewDelegate, UITableViewDataSource, BreakTimeCellDeleagte>
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
BreakTimeCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MY_BREAK_CELL"];
if (cell == nil) {
cell = [BreakTimeCell getBreakTimeCell]; //get the cell
}
cell.cellDelegate = self; //set the delegate to controller (self)
return cell;
}
//this is the delegate method called for the button action.
- (void)breakTimeCell:(BreakTimeCell *)cell didTapTheButton:(UIButton *)aButton {
NSIndexPath *indexPath = [self.personalTable indexPathForCell:cell];
NSLog(#"button tapped for index:%ld",(long)indexPath.row);
}
thats it, you will get output like below,
2017-12-13 11:44:24.693161+0530 Test[3082:100133] button tapped for index:3
2017-12-13 11:44:25.177169+0530 Test[3082:100133] button tapped for index:4
2017-12-13 11:44:26.223166+0530 Test[3082:100133] button tapped for index:0
2017-12-13 11:44:27.663060+0530 Test[3082:100133] button tapped for index:1
2017-12-13 11:44:28.495780+0530 Test[3082:100133] button tapped for index:2
Add this in cellForRow
yourButton.tag = indexPath.row;
[yourButton addTarget:self action:#selector(methodName:) forControlEvents:UIControlEventTouchUpInside];
Perform task in below method
- (void)methodName:(id)sender
{
// you can get index of button from sender.tag
}

UITextField show keyboard on tableviewcell click

I have a simple custom table view cell that has a label and a textfield. Looks like this in the storyboard:
I would like to show the keyboard when the user clicks anywhere in the cell, including if they click the label. I was 99% sure the way to achieve this would be to call becomeFirstResponder when the cell is clicked.
Here is my simple ViewController:
#import "ViewController.h"
#interface ViewController ()
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.dataSource = self;
self.tableView.delegate = self;
[self.tableView setEstimatedRowHeight:44.0f];
[self.tableView setRowHeight:UITableViewAutomaticDimension];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1;
}
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"custom"];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
BOOL firstResponder = [cell becomeFirstResponder];
}
And my custom table view cell:
#import "CustomTableViewCell.h"
#implementation CustomTableViewCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (BOOL) canBecomeFirstResponder {
return YES;
}
- (BOOL) becomeFirstResponder {
return [self.textField becomeFirstResponder];
}
#end
I verified that becomeFirstResponder is called, however that is returning false. What am I missing?
Think as #alex-i points out in a comment here:
This [text field not becoming first responder] can also occur when the textfield is briefly removed from the
view/window hierarchy while becoming the first responder (e.g.
reloading a UITableView or UICollectionView that holds that
textfield).
Which will happen on selection.
Rather than use didSelectRowAtIndexPath, you can add a UITapGestureRecognizer to your tableView with an action like:
- (IBAction)tap:(UITapGestureRecognizer *)sender
{
CGPoint location = [sender locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
BOOL firstResponder = [cell becomeFirstResponder];
}
And it will become first responder.
If someone needs a swift alternative: You can connect outer UIViews with outlet collection. On each UIViewController class you have once call below. So that when the outer box is touched, editfield will be activated with keyboard. You can apply this to your labels as well. (By disabling label's User Interaction)
#IBOutlet var outerBoxes:[UIView]!
override func viewDidLoad() {
super.viewDidLoad();
for outerBox in outerBoxes { outerBox.respondForEditBox() };
...
But once you have to have this code:
extension UIView {
func respondForEditBox() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIView.focusOnEditBox));
self.addGestureRecognizer(tap);
}
func focusOnEditBox() {
for sview in self.subviews {
if sview is UITextField {
sview.becomeFirstResponder();
}
}
}
}
Inspired by #Esqarrouth's answer at
Close iOS Keyboard by touching anywhere using Swift

How to save button selection on UITableViewCell?

My app has a favourite button, on clicking it is converting into red heart and if I click againg then it is back to gray heart. Its working correct. But problem is reuseIdentifier,After scrolling, button just coming to original state because its resusing cell here.
How can I save selection of button so that they remain selected(if selected)
Code of tableViewCell class(.h file):
#import <UIKit/UIKit.h>
#interface favBTNTableViewCell : UITableViewCell
#property(nonatomic)UIButton *faVbtn;
#end
Code of tableViewCell class(.m file)
#import "favBTNTableViewCell.h"
#implementation favBTNTableViewCell
#synthesize faVbtn;
-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(nullable NSString *)reuseIdentifier
{
self=[super initWithStyle:style reuseIdentifier:reuseIdentifier];
if(self)
{
faVbtn=[UIButton new];
[faVbtn setFrame:CGRectMake(10, 10, 25, 25)];
[faVbtn setBackgroundImage:[UIImage imageNamed:#"unsel"] forState:UIControlStateNormal];
[faVbtn addTarget:self action:#selector(clickOnfav) forControlEvents:UIControlEventTouchUpInside];
[faVbtn setSelected:YES];
[self.contentView addSubview:faVbtn];
}
return self;
}
-(void)clickOnfav
{
if ([faVbtn isSelected]) {
[faVbtn setBackgroundImage:[UIImage imageNamed:#"sel.jpg"] forState:UIControlStateNormal];
[faVbtn setSelected:NO];
}
else
{
[faVbtn setSelected:YES];
[faVbtn setBackgroundImage:[UIImage imageNamed:#"unsel"] forState:UIControlStateNormal];
}
}
Code of ViewContrller.m
#import "ViewController.h"
#import "favBTNTableViewCell.h"
#interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
{
NSString *ci;
}
#property (strong, nonatomic) IBOutlet UITableView *tv;
#end
#implementation ViewController
-(NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 30;
}
-(UITableViewCell*)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
favBTNTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:ci];
if(!cell)
{
cell=[[favBTNTableViewCell alloc]init];
cell.faVbtn.tag=indexPath.row;
}
return cell;
}
- (void)viewDidLoad {
_tv.delegate=self;
_tv.dataSource=self;
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
You need corresponding data source for your cells. For this purpose you can, for example, create one more class and you will use it like an item for data source. Take a look:
#interface DataSourceItem : NSObject
#property (nonatomic, assign) BOOL isFavorite;
#end
#implementation DataSourceItem
#end
Then in view controller's code you need to populate array of data source items and manage your table view depending on this array:
#interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
{
NSString *ci;
}
#property (strong, nonatomic) IBOutlet UITableView *tv;
#property (strong, nonatomic) NSArray *dataSourceArray;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_tv.delegate=self;
_tv.dataSource=self;
NSMutableArray *temp = [NSMutableArray new];
// actually how many rows you table view need to have
for (NSUInteger i = 0; i < 30; i++)
{
[temp addObject:[DataSourceItem new]];
}
self.dataSourceArray = [temp copy];**
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// change dataSource item state
DataSourceItem *item = [self.dataSourceArray objectAtIndex:indexPath.row];
item.isFavorite = !item.isFavorite;
// change cell state
favBTNTableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
cell.faVbtn.selected = item.isFavorite;
}
-(NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.dataSource count];
}
-(UITableViewCell*)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
favBTNTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:ci];
if(!cell)
{
cell=[[favBTNTableViewCell alloc]init];
cell.faVbtn.tag=indexPath.row;
}
// decision based on data source item state
cell.favBtn.selected = self.dataSource[indexPath.row];
return cell;
}
You can fix it like this:
Implement - (void)layoutSubviews method in your custom cell.
In - (void)layoutSubviews, check button state and then set the
right image on it:
->
- (void)layoutSubviews {
[super layoutSubviews];
UIImage *buttonImage = [faVbtn isSelected] ? [UIImage imageNamed:#"sel.jpg"] : [UIImage imageNamed:#"unsel"];
[faVbtn setBackgroundImage:buttonImage forState:UIControlStateNormal];
}
if you are using custom cell
register class/nib for your tableview in did load
[tblName registerNib:[UINib nibWithNibName:#"customCell" bundle:nil] forCellReuseIdentifier:#"customCell"];
henceforth in datasource method
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
customCell *cell =(customCell*) [tableView dequeueReusableCellWithIdentifier:#"customCell" forIndexPath:indexPath];
// your code here
return cell;
}
Do not forget to assign your cell identifier as "customCell" in cell attribute
Happy coding..
you can also check similar ans by me
Iphone: Checkmarks in UITableview get mixed up when scrolling

Remove a UITableViewCells button when clicked

I Have a button within a uitableview cell -
I have set it up to trigger a fmethod when clicked - (the function displays messages and resets the message count).
my code for this method is as follows -
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//Define Custom Cells
static NSString *CellCountI =#"CellCount";
UITableViewCell *cell;
feedData *f = [self.HpFeedArray objectAtIndex:indexPath.section];
//Comparison Strings
NSString *count = #"Count";
//If statement Cell Filters
//If Count Cell
if ([f.FeedGroup isEqualToString:count]) {
cell = [tableView dequeueReusableCellWithIdentifier:CellCountI forIndexPath:indexPath];
HP_Header_TableViewCell *hpTC = (HP_Header_TableViewCell *)cell;
hpTC.buttonPressedSelector = #selector(buttonImpMsg);
hpTC.buttonPressedTarget = self;
[hpTC.msgsBtn setTitle: f.FeedTitle forState: UIControlStateNormal];
return hpTC;
}
}
The buttonImpMsg method is as follows -
- (void)buttonImpMsg
{
NSLog(#"Back Button Pressed!");
[self removeBtn];
}
I would like to hide the button when clicked - but I'm not sure how to reference it from the buttonImpMsg method?
Pass the sender to the selector:-
- (void)buttonImpMsg:(id)sender {
[sender removeFromSuperview];
}
You could implement the delegate pattern, IMHO, it's the most proper way.
i think , better will be to make it hidden, if you want to again. – #pawan
I would also hide the button rather than remove it.
Try this implementation to hide the button, you can also do the same thing to hide this one after.
TableViewCell.h:
#import "TableViewCell.h"
#implementation TableViewCell
//.... Connect your action or set selector to this method:
- (IBAction)hideButton:(id)sender
{
UIButton *button = (UIButton *) sender;
// hide the button by using the setter
button.hidden = YES;
//.... Check if the delegate method has been implemented
if ([_delegate respondsToSelector:#selector(hideButton)]) {
[_delegate hideButton];
}
}
#end
TableViewCell.h
//... Declare the delegate:
#protocol CellDelegate <NSObject>
- (void)hideButton;
#end
#interface TableViewCell : UITableViewCell
//... Add a delegate property:
#property (strong, nonatomic) id <CellDelegate> delegate;
#end
ViewController.m:
//... set self a the delegate of your cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//...
cell.delete = self;
return cell;
}
ViewController.m:
//...
#interface ViewController () <CellDelegate>
//...
//... Implement the delegate method if you need to do stuff on the controller side
- (void)hideButton
{
//do stuff here if needed
}

Tableview button get index.row

I got a button in a tableview cell (named "deleteTemplate"), and when it's pressed i should get the "index.row" for the cell the button is in. Anybody knows how to get the "index.row" for the cell, when you click a button in the cell?
My current code for the button:
UITableViewCell *clickedCell = (UITableViewCell *)[[sender superview] superview];
NSIndexPath *clickedButtonIndexPath = [self.tableView indexPathForCell:clickedCell];
NSDictionary *dic = [tableData objectAtIndex:clickedButtonIndexPath.row];
But clickedButtonIndexPath = NULL? :(
This worked in iOS 6.
Thank you!!!
You are getting null because the view hierarchy in iOS 7 is changed.
I recommend to use Delegate for getting the indexpath of TableViewCell.
You can get the sample project from here
Here is the sample:
My View Controller looks like this:
//#import "ViewController.h"
//#import "MyCustomCell.h"
#interface ViewController ()
{
IBOutlet UITableView *myTableView;
NSMutableArray *dataSourceArray;
}
#end
#implementation ViewController
-(void)viewDidLoad
{
[super viewDidLoad];
dataSourceArray = [[NSMutableArray alloc] init];
for(int i=0;i<20;i++)
[dataSourceArray addObject:[NSString stringWithFormat:#"Dummy-%d",i]];
}
-(void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
//pragma mark - UITableView Delegate And Datasource -
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return dataSourceArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdenfifier = #"MyCustomCell";
MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdenfifier forIndexPath:indexPath];
[cell setDelegate:self];
[cell.myButton setTitle:[dataSourceArray objectAtIndex:indexPath.row] forState:UIControlStateNormal];
return cell;
}
//pragma mark - MyCustomCell Delegate -
-(IBAction)myCustomCellButtonTapped:(UITableViewCell *)cell button:(UIButton *)sender
{
NSIndexPath *indexPath = [myTableView indexPathForCell:cell];
NSLog(#"indexpath: %#",indexPath);
}
#end
MyCustomCell.h looks like this:
//#import
#protocol MyCustomCellDelegate
#optional
- (IBAction)myCustomCellButtonTapped:(UITableViewCell *)cell button:(UIButton *)sender;
#end
#interface MyCustomCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UIButton *myButton;
#property(nonatomic, weak)id delegate;
#end
MyCustomCell.m looks like this:
//#import "MyCustomCell.h"
#implementation MyCustomCell
-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
}
return self;
}
-(void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
}
//#pragma mark - My IBActions -
-(IBAction)myCustomCellButtonTapped:(UIButton *)sender
{
if([self.delegate respondsToSelector:#selector(myCustomCellButtonTapped:button:)])
[self.delegate myCustomCellButtonTapped:self button:sender];
}
#end
you set tag for your button in cellforrowatindexpath
clickedButtonIndexPath.tag=indexpath.row;
when button is presse in action write
nslog(#"%i",btutton.tag);
if clickedbuttonindexpath is nil it wont uitableviewcell
This question is already answered many times. For completion, here is the best solution:
-(IBAction)cellButtonTapped:(UIButton *)sender
{
CGRect buttonFrame = [sender convertRect:sender.bounds toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonFrame.origin];
}
when you make the cell assign at you button.tag the indexPath.row and when you click the button in your method you have the sender (the button) and you get the indexPath from the sender's tag

Resources