代码之家  ›  专栏  ›  技术社区  ›  Eric Belair

如何在可编辑组合框中设置文本输入的“maxchars”?

  •  0
  • Eric Belair  · 技术社区  · 16 年前

    我想设置 maxChars 可编辑组合框的文本输入属性。我当前正在使用更改事件将文本剪裁为一组字符数:

    private function nameOptionSelector_changeHandler(event:ListEvent):void
    {
        nameOptionSelector.text = nameOptionSelector.text.substr(0, MAX_LENGTH);
    }
    

    这感觉像是杀戮过度。必须有更好的方法来做到这一点……

    3 回复  |  直到 10 年前
        1
  •  1
  •   Stiggler    16 年前

    你可以延长 ComboBox 并覆盖默认值 maxChars 内部值 TextInput . 如果需要动态设置,可以添加一个公共方法来设置扩展类的属性。

        2
  •  2
  •   Mark Ash    15 年前

    我的选择是直接使用受保护的文本输入。这种方法允许在GUI生成器或代码中设置“maxchars”属性,就像在普通文本字段中一样。请注意,零是maxchars的有效值,表示无限字符。需要重写.childrencreated(),以避免在textinput对象存在之前尝试设置maxchars。

    package my.controls
    {
        import mx.controls.ComboBox;
    
        public class EditableComboBox extends ComboBox
        {
            public function EditableComboBox()
            {
                super();
            }
    
            private var _maxChars:int = 0;
    
            override protected function childrenCreated():void
            {
                super.childrenCreated();
    
                // Now set the maxChars property on the textInput field.
                textInput.maxChars = _maxChars;
            }
    
            public function set maxChars(value:int):void 
            {
                _maxChars = value;
                if (textInput != null && value >= 0)
                    textInput.maxChars = value;
            }
    
            public function get maxChars():int 
            {
                return textInput.maxChars;
            }
    
      }
    }
    
        3
  •  0
  •   Eric Belair    16 年前

    根据Stigler的建议,我实现了以下完整的解决方案:

    package
    {
        import mx.controls.ComboBox;
    
        public class ComboBoxWithMaxChars extends ComboBox
        {
            public function ComboBoxWithMaxChars()
            {
                super();
            }
    
            private var _maxCharsForTextInput:int;
    
            public function set maxCharsForTextInput(value:int):void
            {
                _maxCharsForTextInput = value;
    
                if (super.textInput != null && _maxCharsForTextInput > 0)
                    super.textInput.maxChars = _maxCharsForTextInput;
            }
    
            public function get maxCharsForTextInput():int
            {
                return _maxCharsForTextInput;
            }
    
            override public function itemToLabel(item:Object):String
            {
                var label:String = super.itemToLabel(item);
    
                if (_maxCharsForTextInput > 0)
                    label = label.substr(0, _maxCharsForTextInput);
    
                return label;
            }
        }
    }
    
    推荐文章