我有一个Xamarin Forms项目,我想要一个按钮,必须按长才能触发事件。除了长按事件,我还需要触摸按钮的确切时间,因为那时我想在UI上启动一些动画。
我制作了一个自定义渲染器来解决它,在Android上它可以正常工作,但是在IOS上我遇到了问题:有时它有效,有时却没有。
在IOS上我做到了这样:我使用TouchDown事件来获取触摸的确切时间,TouchUpInside结束和UILongPressGestureRecognizer长按。有时候它就像魅力一样,但有时只会触发UILongPressGestureRecognizer事件而不会触发TouchDown 。
这是我的代码:
[assembly: ExportRenderer(typeof(LongPressButton), typeof(LongPressButtonRenderer))]
namespace AnyProj.iOS
{
public class LongPressButtonRenderer : ButtonRenderer
{
private LongPressButton _longPressButton;
private UILongPressGestureRecognizer _longPressGestureRecognizer;
public LongPressButtonRenderer()
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
_longPressGestureRecognizer = new UILongPressGestureRecognizer(() => HandleLongPress());
if(e.NewElement == null)
{
if (_longPressGestureRecognizer != null)
{
this.RemoveGestureRecognizer(_longPressGestureRecognizer);
}
}
if(e.OldElement == null)
{
_longPressButton = (LongPressButton)e.NewElement;
Control.TouchDown += (sender, ee) => {
Debug.WriteLine("Sometimes triggered, sometimes not.");
};
Control.TouchUpInside += (sender, ee) => {
Debug.WriteLine("Sometimes triggered, sometimes not.");
};
_longPressGestureRecognizer.MinimumPressDuration = 2.0;
this.AddGestureRecognizer(_longPressGestureRecognizer);
}
}
private void HandleLongPress()
{
try
{
if (_longPressGestureRecognizer.State == UIGestureRecognizerState.Began)
Debug.WriteLine("Sometimes triggered, sometimes not.");
}
catch(Exception exc)
{
Debug.Assert(false,exc.Message);
}
}
}
}
你会如此善良地帮助我如何改进它吗?非常感谢!
更新: 它发生在真实设备(IPhone SE)上,在模拟器上它总是像魅力一样!
更新2:我在Swift中做了一个很小的测试项目来实现这个功能,效果很好,所以没有像Xamarin那样的类似错误。
class ViewController: UIViewController {
@IBOutlet weak var longPressButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
longPressButton.addTarget(self, action:#selector(touchDown), for: .touchDown)
longPressButton.addTarget(self, action:#selector(touchUp), for: .touchUpInside)
let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(longTap(_:)))
longGesture.minimumPressDuration = 2.0
longPressButton.addGestureRecognizer(longGesture)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func touchUp(){
print("Touch up")
}
@objc func touchDown(){
print("Touch down")
}
@objc func longTap(_ sender: UIGestureRecognizer){
print("Long tap")
if sender.state == .ended {
print("UIGestureRecognizerStateEnded")
}
else if sender.state == .began {
print("UIGestureRecognizerStateBegan.")
}
}
}
答案 0 :(得分:2)
我在我的项目中测试了以下代码,它运行正常。在iPhone 5c物理设备上测试。请注意,如果长按开始,则不会调用HandleTouchUpInside
;相反,您可以确定UILongPressGestureRecognizer
的{{1}}州的结尾。
UIGestureRecognizerState.Ended