gpt4 book ai didi

ios - 快速通过 UITextField 的 UILongPressGestureRecognizer

转载 作者:搜寻专家 更新时间:2023-10-31 22:41:50 24 4
gpt4 key购买 nike

是否可以在不触发字段编辑的情况下在 UITextField 上使用 UILongPressGestureRecognizer,同时仍然能够通过常规点击编辑文本字段?

我曾尝试向 UITextField 添加长按手势识别器,但长按似乎只在一小部分时间内起作用。

init(frame: CGRect, userCompany: WLUserCompany) {
super.init(frame: frame)

var textField: UITextField?

var longPress = UILongPressGestureRecognizer(target: self, action: #selector(self.longPress(gesture:)))
textField?.addGestureRecognizer(longPress)

self.addSubview(textField!)
}


@objc func longPress(gesture: UILongPressGestureRecognizer) {
if gesture.state == UIGestureRecognizerState.began {
print("Long Press")
}
}

最佳答案

创建 UIGestureRecognizer 的子类

import UIKit.UIGestureRecognizerSubclass

class TouchGestureRecognizer: UIGestureRecognizer {

var isLongPress: Bool = false
fileprivate var startDateInterval: TimeInterval = 0

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesBegan(touches, with: event)
state = .began
self.startDateInterval = Date().timeIntervalSince1970
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesEnded(touches, with: event)
state = .ended
self.isLongPress = (Date().timeIntervalSince1970 - self.startDateInterval) > 1.0
}
}

将手势识别器添加到您的textField

let gesture = TouchGestureRecognizer(target: self, action: #selector(ViewController.textFiledPressed(gesture:)))
self.textField?.addGestureRecognizer(gesture)

现在你可以检查 textFiledPressed(gesture:) 函数是否长按

func textFiledPressed(gesture: TouchGestureRecognizer) {
switch gesture.state {
case .ended:
if gesture.isLongPress {
//Do whatever you need
} else {
self.textField?.becomeFirstResponder()
}

default: break
}

}

关于ios - 快速通过 UITextField 的 UILongPressGestureRecognizer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44910798/

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