Unity之移动设备之IOS调整输入框位置

Unity之移动设备之IOS调整输入框位置,第1张

1,需求:当玩家点击输入框的,会d出虚拟键盘,如果我们的输入框靠下,那么便会被挡住,这个时候如果想要调整输入框位置。
2,思路:这边上移移动的是所有UI的父物体(偷懒了),如果想要移动较小的物体,则可以自行代码调整,就需要判断一下当前输入框所在位置,会不会被虚拟键盘挡住,如果会,则需要上移,上移高度应该上移多少。
3,实现:
3.1 实现的辅佐工具:1,DOTween插件;2,事件管理器(自行封装)。
3.2 虚拟键盘各类信息

using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class KeyBoardMgr
{
    TouchScreenKeyboard keyboard;
    public RectTransform Common=null;
    public KeyBoardMgr()
    {
        EventCenter.AddListener(EventTable.EVE_CloseKeyBoard, CloseKeyBoard);
        //EventCenter.AddListener(EventTable.EVE_Adjustment, AdjustmentUI);
        EventCenter.AddListener<InputField>(EventTable.EVE_InputField, SetInputFieldClick);
        Common = GameObject.Find("Common").GetComponent<RectTransform>();
        EventCenter.AddListener(EventTable.CreateKeyBoard, CreateKeyBoard);
    }
    private void CreateKeyBoard()
    {
        if (keyboard == null)
        {
            keyboard = TouchScreenKeyboard.Open("");
        }
    }
    // Start is called before the first frame update
    void CloseKeyBoard()
    {
        keyboard.active = false;
    }
    public static int GetKeyboardHeight()
    {
        Debug.LogError("键盘高度:" + TouchScreenKeyboard.area.height + ":" + Display.main.systemHeight + ":" + Screen.height);
        return (int)TouchScreenKeyboard.area.height * Display.main.systemHeight / Screen.height;
    }
    private void AdjustmentUI(GameObject gameObject)
    {
//#if Unity_IOS

        float k = gameObject.GetComponent<RectTransform>().anchoredPosition.y;
        Vector2 convertedPosUp = Camera.main.WorldToScreenPoint(gameObject.transform.position);
        Debug.LogError(k + "输入框调整"+"Localpos" + gameObject.GetComponent<RectTransform>().localPosition + convertedPosUp + "Localpos" + gameObject.GetComponent<RectTransform>().anchoredPosition);
        Debug.LogError("输入框调整:传递过来的物体坐标我i" + gameObject.GetComponent<RectTransform>().sizeDelta + ",k为" + k);
        float keyboardHeight = GetKeyboardHeight();
        float keyboardHeightUi = keyboardHeight * k / Display.main.systemHeight;
        Debug.LogError("keyboardHeight" + keyboardHeight + ",keyboardHeightUi为" + keyboardHeightUi);
        //应该显示在这个上面
        float pos = Display.main.systemHeight - keyboardHeightUi;
        Debug.LogError("输入框调整:UI高度和Common高度对比" + keyboardHeightUi + ",Common高度为" + Common.anchoredPosition);
        if (convertedPosUp.y-gameObject.GetComponent<RectTransform>().rect.height < keyboardHeight)
        {

            Common.anchoredPosition = Vector3.up * (convertedPosUp.y + keyboardHeightUi);
        }
        Debug.LogError("输入框调整:调整后的Common高度" + Common.anchoredPosition + ",keyboardHeightUi高度为" + keyboardHeightUi);
        //#endif
    }
    private void SetInputFieldClick(InputField inputField)
    {

        UnityAction<BaseEventData> click = new UnityAction<BaseEventData>(MyClick);
        EventTrigger.Entry myclick = new EventTrigger.Entry();
        myclick.eventID = EventTriggerType.Select;
        myclick.callback.AddListener(click);
        EventTrigger trigger = inputField.gameObject.AddComponent<EventTrigger>();
        trigger.triggers.Add(myclick);
    }
    public void MyClick(BaseEventData data)
    {
        AdjustmentUI(data.selectedObject);
    }

}

3.3 封装,直接将改脚本挂到输入框上面

using DG.Tweening;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;

/// 
/// 移动设备输入框的自适应组件
/// 
public class ChatViewAdaptMobileKeyBoard : MonoBehaviour
{
    public InputField _inputField;

    /// 
    /// 自适应(d出输入框后整体抬高)的面板的初始位置
    /// 
    private Vector2 _adaptPanelOriginPos;
    public RectTransform _adaptPanelRt;
    private float RESOULUTION_HEIGHT = 1280F;


    private void Awake()
    {
        _adaptPanelRt = GameObject.Find("Common").GetComponent<RectTransform>();
        _inputField = GetComponent<InputField>();
        _inputField.onEndEdit.AddListener(OnEndEdit);
        SetInputFieldClick(_inputField);
        _adaptPanelOriginPos = _adaptPanelRt.anchoredPosition;
    }
    private void SetInputFieldClick(InputField inputField)
    {
        UnityAction<BaseEventData> click = new UnityAction<BaseEventData>(MyClick);
        EventTrigger.Entry myclick = new EventTrigger.Entry();
        myclick.eventID = EventTriggerType.Select;
        myclick.callback.AddListener(click);
        EventTrigger trigger = inputField.gameObject.AddComponent<EventTrigger>();
        trigger.triggers.Add(myclick);
    }
    public void MyClick(BaseEventData data)
    {
        Debug2.LogError(transform.name + "点击了当前框");
        isMove = true;
    }
    public bool isMove;
    public float UpHeight;
    private void Update()
    {

                if (_inputField.isFocused)
        {
#if !UNITY_EDITOR
            _inputField.selectionAnchorPosition = _inputField.selectionFocusPosition;

                EventCenter.Dispatch(EventTable.CreateKeyBoard);
                //float keyboardHeight = IOSGetKeyboardHeight() * RESOULUTION_HEIGHT / Screen.height;
                //_adaptPanelRt.anchoredPosition = Vector3.up * keyboardHeight;
                Debug.LogError("键盘高度:" + IOSGetKeyboardHeight() + "屏幕位置" + Camera.main.WorldToScreenPoint(transform.position).y + "自身位置" + transform.position.y + "高度" + transform.GetComponent<RectTransform>().rect.height + "Y:" + transform.GetComponent<RectTransform>().sizeDelta.y);

                    if (DOTween.IsTweening(transform.name))
                    {
                        return;
                    }
                    else {

                    if (Camera.main.WorldToScreenPoint(transform.position).y - transform.GetComponent<RectTransform>().rect.height / 1.5f < IOSGetKeyboardHeight())
                    {
                        float movey = ((IOSGetKeyboardHeight() - Camera.main.WorldToScreenPoint(transform.position).y) + transform.GetComponent<RectTransform>().rect.height) * GameObject.Find("UIRoot").GetComponent<CanvasScaler>().referenceResolution.y / (1.000f * Screen.height);
                            Debug.LogError("键盘高度:" + IOSGetKeyboardHeight() + "屏幕位置" + Camera.main.WorldToScreenPoint(transform.position).y + "自身位置" + transform.position.y + "高度" + transform.GetComponent<RectTransform>().rect.height + "Y:" + transform.GetComponent<RectTransform>().sizeDelta.y);
                            _adaptPanelRt.GetComponent<RectTransform>().DOAnchorPos3DY(movey, 0.5f).SetId(transform.name);
                            isMove = false;
                        }
                    }
#endif
        }
    }

    private void OnValueChanged(string arg0) { }


    /// 
    /// 结束编辑事件,TouchScreenKeyboard.isFocused为false的时候
    /// 
    /// 
    private void OnEndEdit(string currentInputString)
    {
        DOTween.Kill(transform.name);
        isMove = false;
        Debug.LogFormat(transform.name+":OnEndEdit, 输入内容:{0}, 结束时间:{1}", currentInputString, Time.realtimeSinceStartup);
        _adaptPanelRt.anchoredPosition = _adaptPanelOriginPos;
#if UNITY_EDITOR
return;
#endif
        EventCenter.Dispatch(EventTable.EVE_CloseKeyBoard);
    }
    /// 
    /// 结束编辑事件,TouchScreenKeyboard.isFocused为false的时候
    /// 
    /// 
    public void OnSelectEdit(BaseEventData data)
    {
        isMove = true;
    }
    /// 
    /// 获取安卓平台上键盘的高度
    /// 
    /// 
    public int AndroidGetKeyboardHeight()
    {
        using (AndroidJavaClass UnityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        {
            AndroidJavaObject View = UnityClass.GetStatic<AndroidJavaObject>("currentActivity").
                Get<AndroidJavaObject>("mUnityPlayer").Call<AndroidJavaObject>("getView");

            using (AndroidJavaObject Rct = new AndroidJavaObject("android.graphics.Rect"))
            {
                View.Call("getWindowVisibleDisplayFrame", Rct);
                return Screen.height - Rct.Call<int>("height");
            }
        }
    }


    public float IOSGetKeyboardHeight()
    {
#if UNITY_ANDROID
        return AndroidGetKeyboardHeight();
#endif
        return TouchScreenKeyboard.area.height;
    }
}

完毕。如果本文对你有帮助,请点个赞,非常需要你的支持,谢谢

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/993755.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存