Cocos2dx使用TextField实现输入框

时间:2023-02-07 21:13:40

游戏login的时候必须要求玩家输入用户名、密码,还要可以删除。

cocostudio画一个textfield,直接读入好了;

textField类,继承读取的widget。

local textField = class("textField", function GUIReader:shareReader():widgetFromJsonFile(jsonPath)  end)

--获得textField组件

function testField:ctor()

  self.mTextField_input = tolua.cast(Helper:seekWidgetByName(self, "textField_m"), "ccui.TextField")

  self:addCallback()

end

--注册回调

function testField:addCallback()

  local keyListener = cc.EventListenerKeyBoard:create()

  keyListener:registerScriptHandler(handler(self, self.onkeyPressed), cc.Handler.EVENT_KEYBOARD_PRESSED)

  local currentScene = l_command.getCurrentScene()

  currentScene:getEventDispatcher():addEventListenerWithSceneGraphPrioprity(keyListener, currentScene)

  

end

--删除事件,删除字母

function testField:onkeyPressed(keycode, event)

  if keycode == cc.Keycode.KEYBACKSPACE then

     local str = self.mTextField_input:getStringValue()

     str = string.sub(str, 0, string.len(str) - 1)

     self.mTextField_input:setText(str)

  end

end