gpt4 book ai didi

iOS 检测 UIView 的点击和触摸

转载 作者:IT王子 更新时间:2023-10-29 07:43:47 26 4
gpt4 key购买 nike

我遇到了一个问题,即确定如何检测 UIView 被触及和 UIView 被点击。当它被触及时,我希望 UIView 改变它的背景颜色。当它被触摸时,我希望 UIView 执行某些任务。我想知道如何解决这个问题。

-(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");
}

最佳答案

enter image description here

这个方法不需要继承任何东西。您只需将 UILongPressGestureRecognizer 添加到 View 并将 minimumPressDuration 设置为零。然后检查调用手势事件时的状态,看看触摸事件是开始还是结束。

这是上面示例图片的完整项目代码。

import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let tap = UILongPressGestureRecognizer(target: self, action: #selector(tapHandler))
tap.minimumPressDuration = 0
myView.addGestureRecognizer(tap)
}

@objc func tapHandler(gesture: UITapGestureRecognizer) {

// there are seven possible events which must be handled

if gesture.state == .began {
myView.backgroundColor = UIColor.darkGray
return
}

if gesture.state == .changed {
print("very likely, just that the finger wiggled around while the user was holding down the button. generally, just ignore this")
return
}

if gesture.state == .possible || gesture.state == .recognized {
print("in almost all cases, simply ignore these two, unless you are creating very unusual custom subclasses")
return
}

// the three remaining states are
// .cancelled, .failed, and .ended
// in all three cases, must return to the normal button look:
myView.backgroundColor = UIColor.lightGray
}
}

感谢this answer为了这个想法。

关于iOS 检测 UIView 的点击和触摸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19611601/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com