diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e18831..6e7d9c2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,9 @@ Additions - Added a strikethrough formatting code ### MLEM.Ui +Additions +- Allow specifying a maximum amount of characters for a TextField + Improvements - Cache TokenizedString inner offsets for non-Left text alignments to improve performance diff --git a/MLEM.Ui/Elements/TextField.cs b/MLEM.Ui/Elements/TextField.cs index 8d187f1..3495d5a 100644 --- a/MLEM.Ui/Elements/TextField.cs +++ b/MLEM.Ui/Elements/TextField.cs @@ -158,6 +158,11 @@ namespace MLEM.Ui.Elements { this.HandleTextChange(false); } } + /// + /// The maximum amount of characters that can be input into this text field. + /// If this is set, the length of will never exceed this value. + /// + public int? MaximumCharacters; private readonly StringBuilder text = new StringBuilder(); @@ -305,33 +310,40 @@ namespace MLEM.Ui.Elements { /// /// Replaces this text field's text with the given text. + /// If the resulting exceeds , the end will be cropped to fit. /// /// The new text /// If any characters that don't match the should be left out public void SetText(object text, bool removeMismatching = false) { + var strg = text?.ToString() ?? string.Empty; if (removeMismatching) { var result = new StringBuilder(); - foreach (var c in text.ToString()) { + foreach (var c in strg) { if (this.InputRule(this, c.ToCachedString())) result.Append(c); } - text = result.ToString(); - } else if (!this.InputRule(this, text.ToString())) + strg = result.ToString(); + } else if (!this.InputRule(this, strg)) return; + if (this.MaximumCharacters != null && strg.Length > this.MaximumCharacters) + strg = strg.Substring(0, this.MaximumCharacters.Value); this.text.Clear(); - this.text.Append(text); + this.text.Append(strg); this.CaretPos = this.text.Length; this.HandleTextChange(); } /// - /// Inserts the given text at the + /// Inserts the given text at the . + /// If the resulting exceeds , the end will be cropped to fit. /// /// The text to insert public void InsertText(object text) { var strg = text.ToString(); if (!this.InputRule(this, strg)) return; + if (this.MaximumCharacters != null && this.text.Length + strg.Length > this.MaximumCharacters) + strg = strg.Substring(0, this.MaximumCharacters.Value - this.text.Length); this.text.Insert(this.CaretPos, strg); this.CaretPos += strg.Length; this.HandleTextChange();