🔥需求
UGUI,要获取输入框(InputField)的光标在第几行
🔥效果
废话不多说,先来看下效果
🔥设置
需要把原来的InputField组件删除掉,换成InputTest挂载上去,
这几个位置需要重新指定下
🔥源码
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class InputTest : InputField
{
public override void OnPointerDown(PointerEventData eventData)
{
base.OnPointerDown(eventData);
Vector2 localMousePos;
RectTransformUtility.ScreenPointToLocalPointInRectangle(textComponent.rectTransform, eventData.pointerPressRaycast.screenPosition, eventData.pressEventCamera, out localMousePos);
Debug.Log("鼠标点击当前的行数:"+GetUnclampedCharacterLineFromPositions(localMousePos,m_TextComponent.cachedTextGenerator));
}
/// <summary>
/// 返回当前行数
/// </summary>
/// <param name="pos"></param>
/// <param name="generator"></param>
/// <returns></returns>
private int GetUnclampedCharacterLineFromPositions(Vector2 pos, TextGenerator generator)
{
if (!multiLine)
return 0;
float y = pos.y * m_TextComponent.pixelsPerUnit;
float lastBottomY = 0.0f;
for (int i = 0; i < generator.lineCount; ++i)
{
float topY = generator.lines[i].topY;
float bottomY = topY - generator.lines[i].height;
// pos is somewhere in the leading above this line
if (y > topY)
{
// determine which line we're closer to
float leading = topY - lastBottomY;
if (y > topY - 0.5f * leading)
return i - 1;
else
return i;
}
if (y > bottomY)
return i;
lastBottomY = bottomY;
}
// Position is after last line.
return generator.lineCount;
}
}
总结
欢迎大佬多多来给萌新指正,欢迎大家来共同探讨。
如果各位看官觉得文章有点点帮助,跪求各位给点个“一键三连”,谢啦~
声明:本博文章若非特殊注明皆为原创原文链接
https://blog.youkuaiyun.com/Wrinkle2017/article/details/121681714
————————————————————————————————
💢💢版权声明
版权声明:本博客为非营利性个人原创
所刊登的所有作品的著作权均为本人所拥有
本人保留所有法定权利,违者必究!
对于需要复制、转载、链接和传播博客文章或内容的
请及时和本博主进行联系
对于经本博主明确授权和许可使用文章及内容的
使用时请注明文章或内容出处并注明网址
转载请附上原文出处链接及本声明