/// <summary> /// Displays a text field. /// </summary> /// <param name="rect">The rect.</param> /// <param name="str">The string.</param> /// <param name="style">The style.</param> /// <param name="showClearButton">if set to <c>true</c> [show clear button].</param> /// <param name="callback">The callback.</param> /// <returns></returns> public static string TextField(Rect rect, string str, GUIStyle style = null, bool showClearButton = true, Action callback = null) { str = style != null?GUI.TextField(rect, str, style) : GUI.TextField(rect, str); if (showClearButton && !string.IsNullOrEmpty(str) && Button( new Rect(rect.x + rect.width - 12, rect.y + 1, 12, 12), "x", GlobalGUIStyle.WithCenteredFontSize(10))) { // Empty text field when click x str = string.Empty; callback?.Invoke(); } return(str); }
/// <summary> /// Displays a text field. /// </summary> /// <param name="str">The string.</param> /// <param name="style">The style.</param> /// <param name="showClearButton">if set to <c>true</c> [show clear button].</param> /// <param name="callback">The callback.</param> /// <param name="options">The options.</param> /// <returns></returns> public static string TextField(string str, GUIStyle style = null, bool showClearButton = true, Action callback = null, params GUILayoutOption[] options) { var searchRect = style != null ? GUILayoutUtility.GetRect(new GUIContent(str), style, options) : GUILayoutUtility.GetRect(new GUIContent(str), "textField", options); var e = Event.current; var buttonRect = new Rect(searchRect.x + searchRect.width - 12, searchRect.y + 1, 12, 12); var isHovering = buttonRect.Contains(e.mousePosition); var displayCloseButton = showClearButton && !string.IsNullOrEmpty(str); if (!isHovering) { if (style != null) { str = GUI.TextField(searchRect, str, style); } else { str = GUI.TextField(searchRect, str); } } else { GUI.Label(searchRect, str, new GUIStyle("textField") { normal = GUI.skin.textField.focused }); } if (displayCloseButton) { GUI.Label(buttonRect, "x", GlobalGUIStyle.WithCenteredFontSize(10)); if (isHovering && e.rawType == EventType.MouseUp) { // Empty text field when click x str = string.Empty; callback?.Invoke(); } } return(str); }