---
title: "NGUI 实现UIInput按字节长度限制输入"
author: "yangkd548"
date: "2015-01-15T16:36:51Z"
tags: []
categories: ["移动开发"]
slug: "ngui-uiinput"
draft: false
lastmod: "2015-01-16T10:50:29Z"
id: 2176262
url: "https://yangkd548.iteye.com/blog/2176262"
---

UIInput按字节长度限制输入

（汉字算2个字节，数字字母算1个字节）

如果需要限制20个汉字，就需要在页面上配置限制40个字符了。

而数字、字母等都是1个算一个字节，而汉字等算2个字节。

 

- 方法一：在UIInput中进行修改  
  ①增加下面的方法

```
protected int GetStringByteLength(string str)
    {
        byte[] bytestr = System.Text.Encoding.Default.GetBytes(str);
        return bytestr.Length;
    }
```

 ②修改下面的方法

```
public string Validate(string val) 
    { 
        if (string.IsNullOrEmpty(val)) return &quot;&quot;; 

        StringBuilder sb = new StringBuilder(val.Length); 

        for (int i = 0; i  0 &amp;&amp; this.GetStringByteLength(val) &gt;= characterLimit) 
        { 
            do 
            { 
                val = val.Substring(0, val.Length - 1); 
            } while (this.GetStringByteLength(val) &gt; characterLimit); 
        } 
        return val; 
    } 
```

③修改下面的方法

```
protected virtual void Insert(string text)
    {
        string left = GetLeftText();
        string right = GetRightText();
        int rl = right.Length;

        StringBuilder sb = new StringBuilder(left.Length + right.Length + text.Length);
        sb.Append(left);

        // Append the new text
        for (int i = 0, imax = text.Length; i < imax; ++i)
        {
            // Can't go past the character limit
            if (characterLimit > 0 && this.GetStringByteLength(sb.ToString()) + 

this.GetStringByteLength(right) >= characterLimit) break;

            // If we have an input validator, validate the input first
            char c = text[i];
            if (onValidate != null) c = onValidate(sb.ToString(), sb.Length, c);
            else if (validation != Validation.None) c = Validate(sb.ToString(), sb.Length, c);

            // Append the character if it hasn't been invalidated
            if (c != 0) sb.Append(c);
        }

        // Advance the selection
        mSelectionStart = sb.Length;
        mSelectionEnd = mSelectionStart;

        // Append the text that follows it, ensuring that it's also validated after the inserted value
        for (int i = 0, imax = right.Length; i < imax; ++i)
        {
            char c = right[i];
            if (onValidate != null) c = onValidate(sb.ToString(), sb.Length, c);
            else if (validation != Validation.None) c = Validate(sb.ToString(), sb.Length, c);
            if (c != 0) sb.Append(c);
        }

        mValue = sb.ToString();
        UpdateLabel();
        ExecuteOnChange();
    }
```

 

- 方法二：在上层逻辑中实现（推荐此方法）

 

```
    //下面的事件监听放入合适的方法中 调用
    EventDelegate.Add(this.mInput.onChange, this.OnInputChange);

    private void OnInputChange()
    {
        string str = this.mInput.value;
        if (characterLimit > 0 && this.GetStringByteLength(str) > characterLimit)
        {
            do
            {
                str = str.Substring(0, str.Length - 1);
            } while (this.GetStringByteLength(str) > characterLimit);
            this.mInput.value = str;
        }
    }
    private int GetStringByteLength(string str)
    {
        byte[] bytestr = System.Text.Encoding.Default.GetBytes(str);
        return bytestr.Length;
    }

```