Обнаружение касания UIImageView в UITableViewCell - программирование

Обнаружение касания UIImageView в UITableViewCell

У меня есть пользовательский комплекс UITableViewCell, в котором есть много просмотров. У меня есть UIImageView внутри него, который видим для определенного условия. Когда он будет виден,

  • Мне нужно выполнить какое-то действие, когда пользователь Taps делает UIImageView.

  • Я знаю, что мне нужно вызвать селектор для этой задачи. Но я также хочу передать значение этому методу (см. See - (void) onTapContactAdd: (id) отправитель: (NSString *) uid ниже), который будет вызываться как действие касания моего UIImageView в UITableViewCell. Я говорю о, Это потому, что, используя это переданное значение, вызываемый метод будет выполнять эту работу.

Вот что я пробовал до сих пор.

cell.AddContactImage.hidden = NO ;
cell.imageView.userInteractionEnabled = YES;

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapContactAdd::)];
[tap setNumberOfTouchesRequired:1];
[tap setNumberOfTapsRequired:1];
[tap setDelegate:self];
[cell.AddContactImage addGestureRecognizer:tap];



-(void)onTapContactAdd :(id) sender : (NSString*) uid
{
    NSLog(@"Tapped");
// Do something with uid from parameter
}

Этот метод не вызывается при нажатии. Я добавил в свой заголовочный файл.

Спасибо за вашу помощь заранее.

4b9b3361

Ответ 1

Возможно, это не идеальное решение, но добавьте теги к каждому из UIImageView. Затем получим NSArray с uid, соответствующим значениям тега

Итак, где-то в вашем коде сделайте массив

NSArray *testArray = [NSArray arrayWithObjects:@"uid1", @"uid2", @"uid3", @"uid4", @"uid5", @"uid6", nil];

Затем, когда вы настраиваете ячейки tableview, установите тег в строку #

//Set the tag of the imageview to be equal to the row number 
cell.imageView.tag = indexPath.row;

//Sets up taprecognizer for each imageview
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                      action:@selector(handleTap:)];
[cell.imageView addGestureRecognizer:tap];

//Enable the image to be clicked 
cell.imageView.userInteractionEnabled = YES;

Затем в методе, который вызывается, вы можете получить тег, подобный этому

- (void)handleTap:(UITapGestureRecognizer *)recognizer  
{    
     NSString *uid = testArray[recognizer.view.tag];    
}

Ответ 2

Добавьте распознаватель жестов к самой ячейке.

Затем в селекторе действий выполните следующие действия, чтобы узнать, какой вид был использован:

-(IBAction)cellTapped:(UITapGestureRecognizer*)tap
{
    MyCustomTableViewCell* cell = tap.view;
    CGPoint point = [tap locationInView:cell.contentView];
    UIView* tappedView = [cell.contentView hitTest:point withEvent:NULL];

    if (tappedView==cell.myImageView) {
        // Do whatever you want here,
    }
    else { } // maybe you have to handle some other views here
}

Ответ 3

распознаватель жеста передаст только один аргумент в селектор действий: сам. Так что вам нужно передать значение uid самостоятельно. Подобно этому.

Угадай, что это лежит в cellForRowAtIndexPath: method

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //code
    cell.AddContactImage.hidden = NO ;
    cell.imageView.userInteractionEnabled = YES;
    cell_Index=indexPath.row ;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self               action:@selector(onTapContactAdd:)];   //just one arguement passed
    [tap setNumberOfTouchesRequired:1];
    [tap setNumberOfTapsRequired:1];
    [tap setDelegate:self];
    [cell.AddContactImage addGestureRecognizer:tap];
    //rest of code
}

-(void)onTapContactAdd :(NSString*) uid
{
     NSLog(@"Tapped");
     CustomCell *cell=(CustomCell *)[yourtableView cellForRowAtIndexPath:[NSIndexPath  indexPathForRow:cell_Index inSection:0]]; 
     //cell.AddContactImage will give you the respective image .
     // Do something with uid from parameter .
}

Итак, когда вы нажимаете на видимое изображение в соответствующей пользовательской ячейке, метод onTapContactAdd: вызывается с соответствующим значением uid (parameter), и теперь у нас есть cell.AddContactImage, также доступный, который, я считаю, является причиной, почему вы пытались передать его также вместе с параметрами. Надеюсь, что это поможет!!!

Ответ 4

вы можете использовать ALActionBlocks, чтобы добавить жест в UIImageView и обработать действие в блоке

__weak ALViewController *wSelf = self;
imageView.userInteractionEnabled = YES;
UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithBlock:^(UITapGestureRecognizer *weakGR) {
    NSLog(@"pan %@", NSStringFromCGPoint([weakGR locationInView:wSelf.view]));
}];
[self.imageView addGestureRecognizer:gr];

Установить

pod 'ALActionBlocks'

Ответ 5

Еще один, с indexPath, если вам нормально обращаться с краном в DataSource:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseId)! as! ...ListCell
    ...
    cell.theImage.isUserInteractionEnabled = true
    let onTap = UITapGestureRecognizer(target: self, action: #selector(onTapImage))
    onTap.numberOfTouchesRequired = 1
    onTap.numberOfTapsRequired = 1
    cell.theImage.addGestureRecognizer(onTap)
    ...
    return cell
}

func onTapImage(_ sender: UITapGestureRecognizer) {
    var cell: ...ListCell?
    var tableView: UITableView?
    var view = sender.view
    while view != nil {
        if view is ...ListCell {
            cell = view as? ...ListCell
        }
        if view is UITableView {
            tableView = view as? UITableView
        }
        view = view?.superview
    }

    if let indexPath = (cell != nil) ? tableView?.indexPath(for: cell!) : nil {
        // this is it
    }
}

Возможно, вы захотите сделать код короче, если у вас есть только один tableView.

Ответ 6

Здесь у нас есть customtableviewcell как .h, так и .m файлы с двумя изображениями в ячейке. И HomeController, которые имеют tableview для доступа к этой ячейке. Это обнаружение Tap на обоих UIImage, как описано.

            **CustomTableViewCell.h**

            @protocol CustomTableViewCellDelegate <NSObject>

            - (void)didTapFirstImageAtIndex:(NSInteger)index;
            -(void)didTapSettingsImagAtIndex:(NSInteger)index;

            @end


            @interface CustomTableViewCell : UITableViewCell
            {

                UITapGestureRecognizer *tapGesture;
                UITapGestureRecognizer *tapSettingsGesture;


            }

            @property (weak, nonatomic) IBOutlet UIImageView *firstImage;
            @property (weak, nonatomic) IBOutlet UIImageView *lightSettings;

            @property (nonatomic, assign) NSInteger cellIndex;
            @property (nonatomic, strong) id<CustomTableViewCellDelegate>delegate;

            **CustomTableViewCell.m**

            #import "CustomTableViewCell.h"

            @implementation CustomTableViewCell

            - (void)awakeFromNib {
                [super awakeFromNib];
                // Initialization code

                [self addGestures];
            }

            - (void)addGestures {
                tapGesture = [[UITapGestureRecognizer alloc] 
             initWithTarget:self action:@selector(didTapFirstImage:)];
                tapGesture.numberOfTapsRequired = 1;
                [_firstImage addGestureRecognizer:tapGesture];

                tapSettingsGesture = [[UITapGestureRecognizer alloc] 
           initWithTarget:self action:@selector(didTapSettingsImage:)];
                tapSettingsGesture.numberOfTapsRequired = 1;
                [_lightSettings 
            addGestureRecognizer:tapSettingsGesture];
            }

            - (void)didTapFirstImage:(UITapGestureRecognizer *)gesture 
           {
                if (_delegate) {
                    [_delegate didTapFirstImageAtIndex:_cellIndex];
                }
            }

            -(void)didTapSettingsImage: (UITapGestureRecognizer 
            *)gesture {
                if(_delegate) {
                    [_delegate didTapSettingsAtIndex:_cellIndex];
                }
            }


         **HomeController.h**

        #import <UIKit/UIKit.h>
        #import "CustomTableViewCell.h"

        @interface HomeController : CustomNavigationBarViewController 
        <UITableViewDelegate, UITableViewDataSource, 
         UIGestureRecognizerDelegate, CustomTableViewCellDelegate>

        @end

        **HomeController.m**
        ---------------------         

        #import "HomeController.h"
        #import "CustomTableViewCell.h"



        @implementation HomeController


        -(NSInteger)tableView:(UITableView *)tableView 
       numberOfRowsInSection:(NSInteger)section {

        return 2 (Number of rows) ;
         // return number of rows 
    }


         -(UITableViewCell *)tableView:(UITableView *)tableView 
     cellForRowAtIndexPath:(NSIndexPath *)indexPath
        {
           CustomTableViewCell *cell = [tableView 
            dequeueReusableCellWithIdentifier:@"cell" 
            forIndexPath:indexPath];


         cell.delegate = self;
         cell.cellIndex = indexPath.row;
         cell.firstImage.userInteractionEnabled = YES;
         cell.lightSettings.userInteractionEnabled = YES;

         return cell;
         }




        -(void)didTapFirstImageAtIndex:(NSInteger)index
        {
            NSLog(@"Index %ld ", (long)index);
            //Do whatever you want here
        }

        -(void)didTapSettingsAtIndex:(NSInteger)index
        {
            NSLog(@"Settings index %ld", (long)index);
            // Do whatever you want here with image interaction
        }



        @end