HtmlButton.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace FairyGUI.Utils
  5. {
  6. /// <summary>
  7. ///
  8. /// </summary>
  9. public class HtmlButton : IHtmlObject
  10. {
  11. public GComponent button { get; private set; }
  12. public const string CLICK_EVENT = "OnHtmlButtonClick";
  13. public static string resource;
  14. RichTextField _owner;
  15. HtmlElement _element;
  16. EventCallback1 _clickHandler;
  17. public HtmlButton()
  18. {
  19. if (resource != null)
  20. {
  21. button = UIPackage.CreateObjectFromURL(resource).asCom;
  22. _clickHandler = (EventContext context) =>
  23. {
  24. _owner.DispatchEvent(CLICK_EVENT, context.data, this);
  25. };
  26. }
  27. else
  28. Debug.LogWarning("FairyGUI: Set HtmlButton.resource first");
  29. }
  30. public DisplayObject displayObject
  31. {
  32. get { return button != null ? button.displayObject : null; }
  33. }
  34. public HtmlElement element
  35. {
  36. get { return _element; }
  37. }
  38. public float width
  39. {
  40. get { return button != null ? button.width : 0; }
  41. }
  42. public float height
  43. {
  44. get { return button != null ? button.height : 0; }
  45. }
  46. public void Create(RichTextField owner, HtmlElement element)
  47. {
  48. _owner = owner;
  49. _element = element;
  50. if (button == null)
  51. return;
  52. button.onClick.Add(_clickHandler);
  53. int width = element.GetInt("width", button.sourceWidth);
  54. int height = element.GetInt("height", button.sourceHeight);
  55. button.SetSize(width, height);
  56. button.text = element.GetString("value");
  57. }
  58. public void SetPosition(float x, float y)
  59. {
  60. if (button != null)
  61. button.SetXY(x, y);
  62. }
  63. public void Add()
  64. {
  65. if (button != null)
  66. _owner.AddChild(button.displayObject);
  67. }
  68. public void Remove()
  69. {
  70. if (button != null && button.displayObject.parent != null)
  71. _owner.RemoveChild(button.displayObject);
  72. }
  73. public void Release()
  74. {
  75. if (button != null)
  76. button.RemoveEventListeners();
  77. _owner = null;
  78. _element = null;
  79. }
  80. public void Dispose()
  81. {
  82. if (button != null)
  83. button.Dispose();
  84. }
  85. }
  86. }