我用点击手势识别器点击了一个视图,工作得很好。但我希望在触摸发生时突出显示视图,并在触摸结束时将其移除。
我试过这个:
- (IBAction)refresh:(UITapGestureRecognizer *)sender {
if(self.currentStatus == NODATA){
if(sender.state == UIGestureRecognizerStateBegan){
NSLog(@"Began!");
[self.dashboardViewController.calendarContainer state:UIViewContainerStatusSELECTED];
}
if (sender.state == UIGestureRecognizerStateEnded){
NSLog(@"%@", @"Ended");
[self.dashboardViewController.calendarContainer state:UIViewContainerStatusNORMAL];
}
[self setState:REFRESHING data:nil];
}
}
“已完成”的NSLog显示但是开始没有显示,所以它永远不会被选中。这是为什么?
答案 0 :(得分:11)
UITapGestureRecognizer
永远不会进入UIGestureRecognizerStateBegan
州。只有连续手势(例如滑动或捏合)才会使识别器从UIGestureRecognizerStatePossible
转到UIGestureRecognizerStateBegan
。 离散手势,例如点按,将其识别器直接放入UIGestureRecognizerStateRecognized
,即单击一下,直接进入UIGestureRecognizerStateEnded
。
那就是说,也许你正在寻找一个UILongPressGestureRecognizer
,这是一个连续的识别器,它会进入UIGestureRecognizerStateBegan
,让你能够辨别触摸的开始和结束?
答案 1 :(得分:5)
可能为时已晚。但是,如果您严格要使用手势识别器,这也会对您有所帮助。
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]
initWithTarget:self
action:@selector(refresh:)];
longPress.minimumPressDuration = 0.0;
- (IBAction)refresh:(UILongPressGestureRecognizer *)sender {
if(self.currentStatus == NODATA){
if(sender.state == UIGestureRecognizerStateBegan){
NSLog(@"Began!");
[self.dashboardViewController.calendarContainer state:UIViewContainerStatusSELECTED];
}
if (sender.state == UIGestureRecognizerStateEnded){
NSLog(@"%@", @"Ended");
[self.dashboardViewController.calendarContainer state:UIViewContainerStatusNORMAL];
}
[self setState:REFRESHING data:nil];
}
}
答案 2 :(得分:2)
您还可以使用touchesBegan:withEvent:
和touchesEnded:withEvent:
方法。
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSSet *t = [event touchesForView:_myView];
if([t count] > 0) {
// Do something
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
NSSet *t = [event touchesForView:_myView];
if([t count] > 0) {
// Do something
}
}
答案 3 :(得分:0)
let recognizer = UILongPressGestureRecognizer(target: self, action: Selector("touched:"))
recognizer.delegate = self
recognizer.minimumPressDuration = 0.0
addGestureRecognizer(recognizer)
userInteractionEnabled = true
/**
* Gesture handler
*/
@objc func touched(sender: UILongPressGestureRecognizer) {
if sender.state == .began {
/*onPressed*/
} else if sender.state == .ended {
/*onReleased*/
}
}
答案 4 :(得分:0)
一个古老的问题,但仍然存在。希望它将对某人有所帮助。如果我对作者的问题的回答正确,则其目的是检测水龙头是否已开始识别并执行操作。就像您不希望目标仅在用户释放手指时才触发,而在用户第一次触摸时已经触发。
一种简单的方法是对UITapGestureRecognizer
进行扩展,如下所示:
fileprivate class ModTapGestureRecognizer: UITapGestureRecognizer {
var onTouchesBegan: (() -> Void)?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
onTouchesBegan?()
super.touchesBegan(touches, with: event)
}
}
稍后在您的代码中可以像这样使用它:
let tapRecognizer = ModTapGestureRecognizer()
tapRecognizer.addTarget(self, action: #selector(didTapped))
tapRecognizer.onTouchesBegan = {
print("Yep, it works")
}
yourView.addGestureRecognizer(tapRecognizer)
您真棒!