TapGestureRecognizer не вызывается - PullRequest
5 голосов
/ 26 марта 2012

Привет в главном WiewController в viewDidLoad я установил

UIGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(processTap)];

, а затем для цикла я создаю UIViews и добавляю их в представление прокрутки, которое затем добавляется в основной вид.

       UIView *newsContainer = [[UIView alloc] initWithFrame:CGRectMake(160 * countnews, 30, 156, 126)];
       newsContainer.tag = countnews;
       newsContainer.userInteractionEnabled = YES;
       [newsContainer addGestureRecognizer:recognizer];            
       [tempScroll addSubview:newsContainer];

тогда у меня есть функция

- (void)processTap:(UITapGestureRecognizer *)recognizer {
    UIView *view = recognizer.view;
    NSLog(@"HELLO, %d", view.tag);
}

Что никогда не вызывается, какие-либо предложения?Ваша помощь будет принята с благодарностью.Заранее спасибо.

вот и вся .m

#import "iPadMainViewController.h"
#import "GradeintView.h"
#import <QuartzCore/CALayer.h>
#import "Category.h"
#import "News.h"
#import "LazyImageView.h"
#import "TouchView.h"

@interface iPadMainViewController ()

@end

@implementation iPadMainViewController

@synthesize detailsView = _detailsView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(processTap:)];
    [recognizer setDelegate:self];

    GradeintView *MainTitle = [[GradeintView alloc] initWithFrame:CGRectMake(0, 0, 1024, 50)];
    GradeintView *MainSubTitle = [[GradeintView alloc] initWithFrame:CGRectMake(0, 50, 1024, 30)];

    NSMutableArray *categoriesCollection = [[Category alloc] allCategoriesFromFeedAtUrl:@"http://geonews.ge/xml/category.php"];

    UIScrollView *categories = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 512, 768)];
    _detailsView = [[UIWebView alloc] initWithFrame:CGRectMake(500, 0, 512, 768)];
    [_detailsView addGestureRecognizer:recognizer];
    [categories setScrollEnabled:TRUE];
    [categories setContentSize:CGSizeMake(500, categoriesCollection.count * 156)];

    MainTitle.layer.masksToBounds = NO;
    MainTitle.layer.shadowOffset = CGSizeMake(3, 3);
    MainTitle.layer.shadowRadius = 5;
    MainTitle.layer.shadowOpacity = 0.3;

    [categories setBackgroundColor:[UIColor redColor]];

    int counter = 0;

    for (Category *cat in categoriesCollection)
    {
        UIView *categoryTitle = [[UIView alloc] initWithFrame:CGRectMake(0, 166 * counter
                                                                         , 500, 20)];

        UILabel *categoryLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 200, 20)];

        [categoryLabel setBackgroundColor:[UIColor clearColor]];
        NSMutableArray *allCurrentNews = [[News alloc] allNewsFromCategory:cat.CategoryId];

        categoryLabel.text = cat.Name;
        categoryLabel.textColor = [UIColor whiteColor];

        [categoryTitle addSubview:categoryLabel];

        UIColor *myblack = [[UIColor alloc] initWithRed:0.14 green:0.14 blue:0.14 alpha:1];
        UIColor *ligheterBlac = [[UIColor alloc] initWithRed:0.227 green:0.22 blue:0.22 alpha:1];
        [categoryTitle setBackgroundColor:myblack];

        UIScrollView *tempScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 166 * counter, 500, 166)];

        UIColor *tempcolor = ligheterBlac; 
        tempScroll.layer.borderColor = [UIColor colorWithRed:0.34 green:0.34 blue:0.34 alpha:1].CGColor;
        tempScroll.layer.borderWidth = 0.5f;
        int countnews = 0;

        for (News *news in allCurrentNews)
        {
            UIView *newsContainer = [[UIView alloc] initWithFrame:CGRectMake(160 * countnews, 30, 156, 126)];
            newsContainer.tag = countnews;
            [newsContainer addGestureRecognizer:recognizer];

            //newsContainer.NewsId = news.NewsId;
            LazyImageView *image = [[LazyImageView alloc] initWithURl:[NSURL URLWithString:news.Thumbnail]];
            image.frame = CGRectMake(0, 0 , 156, 96);
            UILabel *newsTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 96, 156, 30)];
            newsTitle.backgroundColor = myblack;
            newsTitle.numberOfLines = 2;
            newsTitle.font = [UIFont systemFontOfSize:11];
            newsTitle.text = news.Title;
            newsTitle.textColor = [UIColor whiteColor];
            newsTitle.textAlignment = UITextAlignmentCenter;

            newsContainer.layer.borderColor = [UIColor colorWithRed:0.34 green:0.34 blue:0.34 alpha:1].CGColor;
            newsContainer.layer.borderWidth = 0.5f;

            [newsContainer addSubview:image];
            [newsContainer addSubview:newsTitle];

            countnews ++;
            [tempScroll setContentSize:CGSizeMake(allCurrentNews.count * 156, 96)];
            [tempScroll addSubview:newsContainer];
           //[image release];
        }

        [tempScroll setBackgroundColor: tempcolor];

        [categories addSubview:tempScroll];
        [categories addSubview:categoryTitle];
        [tempcolor release];
        [tempScroll release];
        counter ++;
    }

    self.detailsView.layer.masksToBounds = NO;
    self.detailsView.layer.shadowOffset = CGSizeMake(-10, 5);
    self.detailsView.layer.shadowRadius = 5;
    self.detailsView.layer.shadowOpacity = 0.3;


    [self.detailsView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.amazon.com"]]];
    [self.view addSubview:categories];
    [self.view addSubview:self.detailsView];
    [self.view addSubview:MainSubTitle];
    [self.view addSubview:MainTitle];

}

- (void)processTap:(UITapGestureRecognizer *)recognizer {
    UIView *view = recognizer.view;
    NSLog(@"HELLO, %d", view.tag);
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

- (void)dealloc {
    [super dealloc];
}

- (void)loadDetailedContent:(NSString *)s
{
}

@end

Ответы [ 8 ]

5 голосов
/ 26 марта 2012

Мне кажется, проблема в том, что scrollView, который содержит ваши представления, имеет свой собственный внутренний распознаватель жестов, который «забирает» сенсорные события из вашего распознавателя жестов касания. Попробуйте реализовать следующий метод делегата распознавателя жестов:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}
5 голосов
/ 26 марта 2012

Изменение

initWithTarget:self.view

до

initWithTarget:self

EDIT:
Вы также забыли двоеточие:

initWithTarget:self action:@selector(processTap:)

EDIT2:
Вы создали _detailsView (с назначенным UITapGestureRecognizer), но не добавили его ни в одно подпредставление. Как это будет работать?

4 голосов
/ 17 апреля 2012

Вы проверили настройку взаимодействия?Взаимодействие должно быть установлено на «Взаимодействие с пользователем включено» в инспекторе атрибутов для изображения.

2 голосов
/ 26 марта 2012

Измените @selector (processTap) на @selector (processTap:)

Потому что теперь вы вызываете метод, который не существует.

2 голосов
/ 26 марта 2012

попробуйте этот код

UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(processTap)];
[newsContainer addGestureRecognizer::gestureRecognizer];
 gestureRecognizer.cancelsTouchesInView = NO;
0 голосов
/ 19 февраля 2013

вы можете сначала добавить ваш gestRecognizer в self.view и проверить, вызван или нет ваш метод ... а также проверить эту ветку
Проблема с UITapGestureRecognizer

0 голосов
/ 26 марта 2012

Вы добавляете UIGestureRecognizer к UIWebview, что не рекомендуется. UIWebview has its own UIGestureRecognizer, которые сложно перевезти. См. ТАК вопрос для получения дополнительной информации.

0 голосов
/ 26 марта 2012

Полагаю, проблема в том, что вы, возможно, пропустили добавление <UIGestureRecognizerDelegate> в заголовочный файл.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...