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

iOS自定义Button渲染器:实现TouchUpInside时修改按钮背景色

解决iOS CustomRenderer中按钮TouchUpInside时修改背景色的问题

嘿,这就帮你把这段代码补全并优化!你已经有了不错的开头,只需要完善事件处理逻辑,同时注意避免内存泄漏的小细节。

完整的自定义渲染器代码

public class BtnRendereriOS : ButtonRenderer
{
    private UIButton _nativeButton;

    protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
    {
        base.OnElementChanged(e);

        // 移除旧控件的事件订阅,防止内存泄漏
        if (e.OldElement != null && _nativeButton != null)
        {
            _nativeButton.TouchUpInside -= OnButtonTapped;
        }

        if (Control != null)
        {
            _nativeButton = Control;
            // 设置初始背景色
            _nativeButton.BackgroundColor = UIColor.FromRGB(3, 169, 244);
            _nativeButton.Layer.CornerRadius = 0;
            
            // 订阅TouchUpInside点击事件
            _nativeButton.TouchUpInside += OnButtonTapped;
        }
    }

    private void OnButtonTapped(object sender, EventArgs e)
    {
        // 这里修改触摸后的背景色,比如换成深一号的蓝色
        if (_nativeButton != null)
        {
            _nativeButton.BackgroundColor = UIColor.FromRGB(2, 136, 209);
            // 如果需要模拟"按压回弹"效果,可加延迟恢复原颜色:
            // Task.Delay(200).ContinueWith(_ => 
            // {
            //     InvokeOnMainThread(() => 
            //     {
            //         _nativeButton.BackgroundColor = UIColor.FromRGB(3, 169, 244);
            //     });
            // });
        }
    }

    protected override void Dispose(bool disposing)
    {
        // 销毁时务必取消事件订阅,彻底避免内存泄漏
        if (disposing && _nativeButton != null)
        {
            _nativeButton.TouchUpInside -= OnButtonTapped;
        }
        base.Dispose(disposing);
    }
}

几个关键细节说明

  • 事件订阅的清理:在OnElementChanged里处理旧控件的事件移除,再在Dispose方法里二次清理,这是自定义渲染器里防止内存泄漏的核心操作,千万别漏!
  • 安全访问原生控件:把Control赋值给类级别的_nativeButton变量,这样在事件方法里能避免空引用异常,操作更稳妥。
  • UI操作的线程要求:如果用延迟任务恢复背景色,一定要用InvokeOnMainThread包裹,iOS的UI操作必须在主线程执行,不然会出问题。

这样就能完美实现你要的“触摸按钮时修改背景色”的需求啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:23:04