• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Unity主动聚焦InputField并且设置光标位置

武飞扬头像
人生若只如初見♫
帮助1

前言

在一次文本输入的设计中,需要用到点击自定义的Button来删除InputField里对应光标位置的字符,并且保持InputField和光标不会丢失焦点

  1. 实现删除字符

  1. 实现InputField焦点不丢失

  1. 实现光标不消失

  1. 解决光标重设时,由于自动SelectAll时导致的选中颜色闪烁

各位有更优的办法可以分享分享 thanks~~

解决方法

  1.  
    private InputField m_MainIPF;
  2.  
    private int m_CurrentCaretPosition;
  3.  
    private Color m_MainIPF_selectionColor;
  4.  
    private Button m_DelBtn;
  5.  
    Start()
  6.  
    {
  7.  
        m_MainIPF.onEndEdit.AddListener((value)=> {
  8.  
    m_CurrentCaretPosition = m_MainIPF.caretPosition;
  9.  
    });
  10.  
       m_DelBtn.onClick.AddListener(OnClickDelBtn);
  11.  
    }
  12.  
    private void OnClickDelBtn()
  13.  
    {
  14.  
    var value = m_MainIPF.text;
  15.  
    if (value.Length >= m_CurrentCaretPosition && m_CurrentCaretPosition > 0)
  16.  
    {
  17.  
    m_CurrentCaretPosition--;
  18.  
    value.Remove(m_CurrentCaretPosition, 1);
  19.  
            m_MainIPF.text = value;
  20.  
    }
  21.  
    GameEntry.Instance.StartCoroutine(ResetInputFieldCaret());
  22.  
    }
  23.  
    IEnumerator ResetInputFieldCaret()
  24.  
    {
  25.  
    if (!m_MainIPF.isFocused)
  26.  
    {
  27.  
    m_MainIPF.ActivateInputField();//主动选中输入框,但是会自动执行SelectAll,未知原因
  28.  
    var color = m_MainIPF_selectionColor;
  29.  
    color.a = 0;//这里暂时使用的改变颜色来避免SelectAll导致的闪烁
  30.  
    m_MainIPF.selectionColor = color;
  31.  
    }
  32.  
    yield return new WaitForEndOfFrame();//需要延迟一帧后设置光标才会生效
  33.  
    m_MainIPF.caretPosition = m_CurrentCaretPosition;
  34.  
    m_MainIPF.ForceLabelUpdate();//立即强制刷新光标显示,否则会在下一帧才生效
  35.  
    m_MainIPF.selectionColor = m_MainIPF_selectionColor;
  36.  
    }
学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhibfabf
系列文章
更多 icon
同类精品
更多 icon
继续加载