问题描述
我遇到了一个确定如何检测UIView被触及和UIView被轻击的问题。当它被触及时,我希望UIView改变它的背景颜色。当它被触摸时,我希望UIView执行某些任务。我想知道我是如何解决这个问题的。
I am stuck with a problem of determining how to detect a UIView being touched down and UIView being tapped. When it is touched down, I want the UIView to change its background color. When it is touched, I would like the UIView to perform certain tasks. I would like to know how I am able to fix this problem.
-(void)viewDidLoad
{
UITapGestureRecognizer *dismissGestureRecognition = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDismissDoubleTap:)];
dismissGestureRecognition.numberOfTapsRequired = 1;
[sectionDismissDoubleView addGestureRecognizer:dismissGestureRecognition];
UITapGestureRecognizer *dismissGestureDownRecognition = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissGestureDownRecognition:)];
dismissGestureRecognition.numberOfTouchesRequired = 1;
[sectionDismissDoubleView addGestureRecognizer:dismissGestureDownRecognition];
}
- (void)handleDismissDoubleTap:(UIGestureRecognizer*)tap {
SettingsDismissDoubleViewController *settingsDouble = [[SettingsDismissDoubleViewController alloc] initWithNibName:@"SettingsDismissDoubleViewController" bundle:nil];
[self.navigationController pushViewController:settingsDouble animated:YES];
}
- (void)dismissGestureDownRecognition:(UIGestureRecognizer*)tap {
NSLog(@"Down");
}
推荐答案
手势识别器可能过度杀伤力为了你想要的。您可能只想使用 -touchesBegan:withEvent:
和 -touchesEnded:withEvent:
的组合。
A Gesture Recognizer is probably overkill for what you want. You probably just want to use a combination of -touchesBegan:withEvent:
and -touchesEnded:withEvent:
.
这是有缺陷的,但它应该会让你知道你想做什么。
This is flawed, but it should give you and idea of what you want to do.
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
self.touchDown = YES;
self.backgroundColor = [UIColor redColor];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
// Triggered when touch is released
if (self.isTouchDown) {
self.backgroundColor = [UIColor whiteColor];
self.touchDown = NO;
}
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
// Triggered if touch leaves view
if (self.isTouchDown) {
self.backgroundColor = [UIColor whiteColor];
self.touchDown = NO;
}
}
此代码应位于<$的自定义子类中您创建的c $ c> UIView 。然后使用此自定义视图类型而不是 UIView
,您将获得触摸处理。
This code should go in a custom subclass of UIView
that you create. Then use this custom view type instead of UIView
and you'll get touch handling.
这篇关于iOS检测点击并修改UIView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!