这个类定义了键盘处理接口。如果想对键盘输入做处理,可以继承这个委托类。
看看他在哪被用到。
从这幅图看出他的使用过程。先是CCTextFieldTTF继承了CCIMEDelegate,创建时,就会被加入到键盘输入分发器的分发对象中。
@brief A simple text input field with TTF font.
*/
class CC_DLL TextFieldTTF : public Label, public IMEDelegate
{
public:
。。。
protected:
//
// IMEDelegate interface
//
virtual bool canAttachWithIME() override;
virtual bool canDetachWithIME() override;
virtual void insertText(const char * text, size_t len) override;
virtual void deleteBackward() override;
virtual const std::string& getContentText() override;
。。。
}
IMEDelegate::IMEDelegate()
{
IMEDispatcher::sharedDispatcher()->addDelegate(this);
}
然后键盘输入分发器CCIMEDispatcher接收到键盘输入事件。将键盘的输入信息通过CCIMEDelegate的几个接口发送给分发对象。
void IMEDispatcher::dispatchInsertText(const char * text, size_t len)
{
do
{
CC_BREAK_IF(! _impl || ! text || len <= 0);
// there is no delegate attached to IME
CC_BREAK_IF(! _impl->_delegateWithIme);
_impl->_delegateWithIme->insertText(text, len);
} while (0);
}
void IMEDispatcher::dispatchDeleteBackward()
{
do
{
CC_BREAK_IF(! _impl);
// there is no delegate attached to IME
CC_BREAK_IF(! _impl->_delegateWithIme);
_impl->_delegateWithIme->deleteBackward();
} while (0);
}
最后CCTextField通过实现这几个接口来处理输入事件。
void TextFieldTTF::insertText(const char * text, size_t len)
{
std::string insert(text, len);
// insert \n means input end
int pos = static_cast<int>(insert.find('\n'));
if ((int)insert.npos != pos)
{
len = pos;
insert.erase(pos);
}
if (len > 0)
{
if (_delegate && _delegate->onTextFieldInsertText(this, insert.c_str(), len))
{
// delegate doesn't want to insert text
return;
}
_charCount += _calcCharCount(insert.c_str());
std::string sText(_inputText);
sText.append(insert);
setString(sText);
}
if ((int)insert.npos == pos) {
return;
}
// '\n' inserted, let delegate process first
if (_delegate && _delegate->onTextFieldInsertText(this, "\n", 1))
{
return;
}
// if delegate hasn't processed, detach from IME by default
detachWithIME();
}
注意:MEDelegate::attachWithIME()表示准备接受输入信息,一般在控件被点击时(接收信息前)要调用,否则insertText这个接口将不会被调用。