2019-11-21

[Cocos Creator] 畫面縮放改變後 EditBox 輸入區顯示位置異常問題

Cocos Creator 版本: 2.2.0
問題: 畫面縮放改變後 cc.EditBox 輸入區顯示位置異常

修正方式: 增加 Component 動態修正位置
  1. const { ccclass, property, requireComponent } = cc._decorator;
  2. @ccclass
  3. @requireComponent(cc.EditBox)
  4. export default class EditBoxFix extends cc.Component {
  5.  
  6. // 修正 EditBox 在網頁縮放後 輸入區顯示位置異常的問題
  7. // 參考資料
  8. // https://github.com/cocos-creator/engine/blob/2.2.0/cocos2d/core/components/editbox/CCEditBox.js
  9. private canvasWidth: number = 0;
  10. private canvasHeight: number = 0;
  11.  
  12. onLoad(): void {
  13. this.canvasWidth = cc.game.canvas.width;
  14. this.canvasHeight = cc.game.canvas.height;
  15. window.addEventListener("resize", this.onResize);
  16. window.addEventListener("orientationchange", this.onResize);
  17. }
  18.  
  19. onDestroy(): void {
  20. window.removeEventListener("resize", this.onResize);
  21. window.removeEventListener("orientationchange", this.onResize);
  22. }
  23.  
  24. private onResize = (e: Event): void => {
  25. if (this.canvasWidth === cc.game.canvas.width
  26. && this.canvasHeight === cc.game.canvas.height) { return; }
  27. this.resetSize();
  28. }
  29.  
  30. public resetSize = (): void => {
  31. this.canvasWidth = cc.game.canvas.width;
  32. this.canvasHeight = cc.game.canvas.height;
  33. let editBox: any = this.node.getComponent(cc.EditBox);
  34. if (editBox == null) { return; }
  35. let isFocused: any = editBox.isFocused();
  36. if (editBox._impl) {
  37. editBox._impl.clear();
  38. } else {
  39. return;
  40. }
  41. let EditBoxClass: any = cc.EditBox;
  42. let impl: any = editBox._impl = new EditBoxClass._ImplClass();
  43. impl.init(editBox);
  44. editBox._updateString(editBox._string);
  45. editBox._syncSize();
  46. if (isFocused) { editBox.focus(); }
  47. }
  48. }

參考資料
GitHub cocos-creator

沒有留言:

張貼留言