How IOS gets the indexpath.row of the cell that corresponds to the button on the cell

Source: Internet
Author: User

  Create a button in a custom cell in UITableView or Uicollectionview, and when you click the button, the cell that contains the button is in uitableview or Uicollectionview the number of rows in the. Is the cell's indexpath.row, the following take UITableView as an example:

There are two ways of doing this:
-(ibaction):(ID) sender
{

1. The first method, this convenience a little bit, do not set tag.

NSLog (@ "myrow:%d", [Self.tableindexpathforcell: ((tableviewcell*) [[Sender Superview]superview])].row); 2. The second method, this needs to load the cell when the tag is set. but also very convenient.
NSLog (@ "myrow:%d", ((tableviewcell*) [[Sendersuperview]superview]). tag);

}
The code that needs to be added in the Uitableviewdatasource protocol method:
-(UITableViewCell *) TableView: (UITableView *) TableView
Cellforrowatindexpath: (Nsindexpath *) Indexpath
{
Remove all content from Cell.contentview to avoid creating new duplicates below
int i =[[cell.contentview subviews] count]-1;
for (; i>= 0; i--)
{
[[[Cell.contentview subviews] objectatindex:i]removefromsuperview];
}

Add button
Uibutton*but = [UIButton buttonwithtype:uibuttontypecustom];
[Butsetbackgroundimage:[uiimage imagenamed:@ "Delete.png"]forstate:uicontrolstatenormal];
[Butsetframe:cgrectmake (280, 10, 30, 30)];
[butsetalpha:0.8];
[Butaddtarget:self Action: @selector (del:) forcontrolevents:uicontroleventtouchupinside];
[Cell.contentview addsubview:but];
Set the tag to the cell corresponding to the Indexpath row
For (ID viewin subviews)
{
if ([View Iskindofclass:[uibutton class]])
{
[View Settag:[indexpath row];
[Cell.contentview Bringsubviewtofront:view];
}
}
}
Button Event
-(void) del: (ID) sender
{
For (UITableViewCell *cell in Visiblecells)
{
if (Cell.tag = = Button.tag)
{
Button.tag is the corresponding [Indexpath.row
}

How IOS gets the indexpath.row of the cell that corresponds to the button on the cell

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.