这篇文章将为大家详细讲解有关使用UGUI怎么实现一个4位数验证码功能,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
预制体结构:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class VerifyCodePanel : ILoginChild
{
public const int VERIFY_CODE_LENGTH = 4;
public InputField VCodeInput;
public Text[] VCodes = new Text[VERIFY_CODE_LENGTH];
//外部选择蓝色与灰色,分别表示已输入(Blue)和未输入(Gray)
public Color Blue;
public Color Gray;
private int m_lastVcodeLength = 0;
void Start()
{
//外部设置VCodeInput等组件,或使用代码获取,这必须在初始化或之前设置完成
//UIUtility是自己实现的一个针对UI组件获取与绑定的一个工具
VCodeInput = UIUtility.GetChildControl<InputField>("VCodeInput", transform);
BindUIEvents();
}
private void BindUIEvents()
{
//绑定VCodeInput的值变化,外部绑定和代码绑定皆可,这里使用的是自己实现的一个UI工具
UIUtility.BindUIEvent(EventTypeEnum.InputFieldOnValueChanged,
OnVCodeValueChanged, VCodeInput.transform);
}
// 监听输入的字符变化
private void OnVCodeValueChanged(string value)
{
//外部已经设置好VCodeInput的长度限制,最多为4,但是为了避免意外情况,限制字符长度
if (value.Length < 0 || value.Length > 4)
{
return;
}
//判断字符是边长了还是变短了,用以决定Text的跳转方向
bool next = false;
//分割字符,默认为空,如果是长度增加,则说明输入了新的验证码,将这个验证码记录下来
string character = string.Empty;
//比较与上一次输入的验证码长度,缺省长度为0
if(value.Length > m_lastVcodeLength)
{
next = true;
character = value[value.Length - 1].ToString();
}
m_lastVcodeLength = value.Length;
int which = value.Length - 1;
OnMoveCursor(next, which, character);
}
//移动光标(实际上是操作用来显示验证码的Text)
private void OnMoveCursor(bool next, int which, string character)
{
//将值赋给对应的Text
if (next)
{
VCodes[which].text = character;
SetLineColor(which, Blue);
}
else
{
/*这里比较绕,如果是回退,则说明当前的which其实是已经退格后的位数,
* 比如说,原本是输入了123,退格后则变成了12,
* 那么which的值为value.length - 1 = 1; value.length为2
* 而我们需要将原本第三位(从0开始计数,值为2)的Text设置为空
* 因此需要i + 1,而为了避免用户全选并删除所有验证码的情况,需要遍历
*/
for (int i = which; i < VERIFY_CODE_LENGTH - 1; ++i)
{
VCodes[i + 1].text = character;
SetLineColor(i + 1, Gray);
}
}
}
//设置相应Text的Line的颜色
private void SetLineColor(int which, Color color)
{
VCodes[which].transform.GetChild(0).GetComponent<Image>().color = color;
}
}
关于使用UGUI怎么实现一个4位数验证码功能就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。