You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin iOS中UILongPressGestureRecognizer长按重复触发解决方法

Xamarin iOS 长按手势重复触发解决方案

问题原因

UILongPressGestureRecognizer 属于连续型手势识别器,会在手势的全生命周期(识别成功、状态变更、结束、失败)多次触发绑定的回调方法,你最初的实现没有判断手势状态,因此每次触发回调都会执行变量翻转逻辑,出现重复调用的问题。

可用解决方案

方案1:判断手势触发状态(最常用,你找到的方案)

仅当手势第一次识别成功(状态为UIGestureRecognizerState.Began)时执行业务逻辑,后续状态变更不会触发逻辑,代码如下:

public override void AwakeFromNib()
{
    base.AwakeFromNib();
    // 注意回调方法要支持接收UILongPressGestureRecognizer参数
    longp = new UILongPressGestureRecognizer(LongPress);
    button.AddGestureRecognizer(longp);
}

public void LongPress(UILongPressGestureRecognizer g)
{
    if (g.State == UIGestureRecognizerState.Began)
    {
        // 变量翻转逻辑可以简化为直接取反,无需写if else
        a = !a;
    }
}

方案2:执行逻辑后直接禁用手势

如果需要执行一次长按逻辑后完全关闭该手势识别能力,可以在逻辑执行后将手势的Enabled属性设为false,需要恢复时再重新设为true即可:

public void LongPress(UILongPressGestureRecognizer g)
{
    if (g.State == UIGestureRecognizerState.Began)
    {
        a = !a;
        // 禁用当前手势,不会再触发回调
        g.Enabled = false;
    }
}

方案3:移除手势识别器

如果后续再也不需要该长按功能,可以直接将手势从按钮上移除:

public void LongPress(UILongPressGestureRecognizer g)
{
    if (g.State == UIGestureRecognizerState.Began)
    {
        a = !a;
        // 从按钮上移除长按手势
        button.RemoveGestureRecognizer(g);
    }
}

内容的提问来源于stack exchange,提问作者user16384840

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 16:48:05