Hello, I ran into a misunderstanding of how to implement the following construction:

There is a table on the view, in each cell of which there is a button, the touch event of the button must start the function and pass to it the section indexes and the cell row in which the button is located.

Help to correctly register the buttons and get the necessary indexes

  • why don't you want to use a method instead of buttons? - (void) tableView: (UITableView *) tableView didSelectRowAtIndexPath: (NSIndexPath *) indexPath to get the section: [UITableView numberOfSections] - tragvar
  • because when the cell touches, one event occurs, and when the button is touched, another;) I need to process them separately and perform different actions - atom-22
  • one
    I hope my answer will help you. - alexruden

2 answers 2

Custom cells? Fine. Look:

1. create a UIButton subclass (IndexedButton for example), add a property to it

@property (nonatomic) NSIndexPath *button_indexPath; 

In IndexedButton.m, do @synthesize button_indexPath;

2. In the class of your custom cell in the .h file you connect this IndexedButton:

  #import "IndexedButton.h" 

and the button to be pressed is not done by UIButton , but by IndexedButton :

 @property (nonatomic, retain) IBOutlet IndexedButton *buttonInCell; 

In the custom cell m-file, make @synthesize buttonInCell;

There you add this button to the cell in the method:

 -(id)initWithFrame:(CGRect)frame{ self = [super initWithFrame:frame]; if (self){ buttonInCell = [[IndexedButton alloc] initWithFrame:CGRectMake(0,0,50,30)]; [self addSubview:buttonInCell]; // здесь еще твой код } return self; } 

3. Almost all. Now in the main class, the cellForRowAtIndexPath method:

 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*) indexPath { // тут подключение твоей кастомной ячейки if (cell == nil) { //Создание ячейки cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } cell.buttonInCell.button_indexPath = indexPath; //присваиваем кнопке значение indexPath [cell.buttonInCell addTarget:self action:@selector(MyMethod:) forControlEvents:UIControlEventTouchUpInside]; //устанавливаем обработчик для нажатия кнопки // здесь еще твой код return cell; } 

4. Finish- MyMethod method:

 -(IBAction)MyMethod:(id)sender{ NSIndexPath *path = [sender button_indexPath]; //извлекаем IndexPath с кнопки. //наслаждаемся результатом NSLog(@"секция = %i", path.section); NSLog(@"ряд = %i", path.row); } 

Hope clarified available.

  • Yes, subclasses created - atom-22

Create a subclass of the cell:

 @interface MyButtonedCell : UITableViewCell @property (nonatomic, copy) void (^buttonPressedHandler)(void); @end 

No matter how you create the cell, suppose it is a Xib or storyboard:

 @implementation MyButtonedCell - (IBAction)buttonPressed:(id)sender { if (self.buttonPressedHandler) self.buttonPressedHandler(); } @end 

Next, a well-known method from the UITableViewDataSource :

 - (UITableViewCell *)tableView:(UITableView *)tableView cellFoRowAtIndexPath:(NSIndexPath *)indexPath { MyButtonedCell *cell = [tableView dequeReusableCellWithIdentifier:@"MyCellIdentifier"]; /* конфигурим нашу ячейку как обычно */ /* создаем слабую ссылку на self для использования внутри блока, избегаем таким образом ритэйн лупа. Этот пункт ОБЯЗАТЕЛЕН К ИСПОЛНЕНИЮ, нельзя так просто взять и ИСПОЛЬЗОВАТЬ self внутри этого блока, только СЛАБУЮ ССЫЛКУ */ __weak MyTableViewController *self_ = self; cell.buttonPressedHandler = ^{ /* делаем тут что хотим по нажатию кнопки в ячейке с доступным нам тут indexPath*/ [self_ doSomethingByPressButtonAtObject: self_.items[indexPath.row]]; }; return cell; }