此时,Lua 和 iOS 环境之间的通信通过CoronaView 实例允许从一个环境发送事件到另一个环境。
在 Obj-C 中,这些事件由 NSDictionary 实例表示。在 Lua 中,它们是基本的 Lua 表。两者都遵循 Corona 对具有必需 "name" 的事件的约定,该事件会产生一个用于识别 key 的字符串值。此外,还可以通过一系列
在 Obj-C 方面,可以通过构建CoronaView 实例发送事件。例如,如果你有一个应该在 CoronaView 实例内触发事件的 UIButton,那么可以创建一个新的 NSDictionary 实例,为其填充你要传递的信息,然后发送事件。在 Lua 部分,CoronaView 会将此 NSDictionary 对象转换为 Lua 表,并将其分派给注册为侦听该事件的任何 Lua Runtime 侦听器。
以下示例说明了在
// [Obj-C]
CoronaView *view = ...
NSDictionary *event = [NSDictionary dictionaryWithObjectsAndKeys:
@"pauseEvent", @"name",
@"pause", @"phase",
@"otherValue", @"otherKey",
nil];
[view sendEvent:event];
-- [Lua]
local function handlePause( event )
if ( event.phase == "pause" ) then
print( event.name ) --> pauseEvent
print( event.otherKey ) --> otherValue
-- Handle pause implementation here
end
return true
end
Runtime:addEventListener( "pauseEvent", handlePause )
CoronaView 实例中的 Lua 代码可以向 CoronaView 发送事件。这些事件应为 coronaView 类型,你必须注册一个 CoronaViewDelegateCoronaView)以侦听它们event 表在被委托接收时会转换为 NSDictionary。
以下示例说明了在
// [Obj-C]
// Change the value of the UILabel element 'myLabel'
- (id)coronaView:(CoronaView *)view receiveEvent:(NSDictionary *)event
{
NSLog( @"Logging properties of the event: %@", event );
self.myLabel.text = [event objectForKey:@"message"];
return @"Nice to meet you CoronaCards!";
}
-- [Lua]
local function pressMe( event )
if ( event.phase == "ended" ) then
local event = { name="coronaView", message="Hello from CoronaCards!" }
-- Dispatch the event to the global Runtime object
local result = Runtime:dispatchEvent( event )
print( "Response: " .. result ) --> Response: Nice to meet you CoronaCards!
end
return true
end
myObject:addEventListener( "touch", pressMe )
桥接
⟨ Obj-C/UIKit 集成 | 功能比较 ⟩