将事件添加到以编程方式生成的UIView中

时间:2012-12-15 12:24:31

标签: ios objective-c cocoa-touch uiview

所以我有一个方法,然后在调用时生成一个带有一些标签的简单UIView:

UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 300, 250)];
view1.backgroundColor = [UIColor redColor];
view1.userInteractionEnabled = YES;
[self.view addSubview:view1];

我将此方法称为6次,因此它会在屏幕周围放置6个UIViews(我当然给它们提供不同的坐标)。

如何检测用户何时向右滑动然后触发其他方法? 我尝试过这样的事情:

UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(myLabel1Tap)];
swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
[view1 addGestureRecognizer:swipeRight];

然后是一个方法:

- (void)myLabel1Tap {
}

但是我不确定在该方法中该怎么做,如果它们被称为相同的'view1',我怎么知道哪个视图被刷过?

1 个答案:

答案 0 :(得分:4)

更改手势识别器选择器以接受参数(通过在方法签名后添加冒号)

UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(myLabel1Swipe:)];

这意味着手势识别器将被传入,然后您可以基于手势识别器属性执行操作,例如,

- (void)myLabel1Swipe:(UISwipeGestureRecognizer *)recogniser
{
    UIView *swipedView = [recognizer view];
    //do whatever you want with this view
}