我想设置maxChars
可编辑组合框的 TextInput 的属性。我目前正在使用更改事件将文本修剪为一定数量的字符:
private function nameOptionSelector_changeHandler(event:ListEvent):void
{
nameOptionSelector.text = nameOptionSelector.text.substr(0, MAX_LENGTH);
}
这感觉有点矫枉过正。必须有更好的方法来做到这一点......
我想设置maxChars
可编辑组合框的 TextInput 的属性。我目前正在使用更改事件将文本修剪为一定数量的字符:
private function nameOptionSelector_changeHandler(event:ListEvent):void
{
nameOptionSelector.text = nameOptionSelector.text.substr(0, MAX_LENGTH);
}
这感觉有点矫枉过正。必须有更好的方法来做到这一点......
我的替代方法是直接使用受保护的 textInput。这种方法允许在 GUI 构建器或代码中设置“maxChars”属性,就像对普通 TextField 所做的那样。请注意,零是 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;
}
}
}
您可以扩展ComboBox
和覆盖 internal 的默认maxChars
值TextInput
。如果您需要动态设置它,您可以添加一个公共方法来设置扩展类的属性。
使用斯蒂格勒的建议,这是我实现的完整解决方案:
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;
}
}
}