是否可以在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")
}
}
答案 0 :(得分:2)
创建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
}
}
向您的recognizer
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
}
}
答案 1 :(得分:0)
在查看类似的SO here和here并尝试自己之后,我认为这是不可能的 - 至少就是您描述意图的方式。
我能够使用手势控制添加背景视图,但手势与文本字段上的用户交互冲突。不会在文本字段旁边的按钮创建更好的用户体验吗?
FWIW,这是使用双击添加背景UIView
的代码。长按手势有相同的结果
@IBOutlet weak var backgroundView: UIView!
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.myTextFieldTapped))
tapGesture.numberOfTapsRequired = 2
backgroundView.addGestureRecognizer(tapGesture)
}
@objc func myTextFieldTapped() {
print("Double tapped on textField")
}
以下是故事板的图片: