定义一个View和ViewGroup
类,View可以自定义的onDraw
方法,遍历ViewGroup中的所有View对象,执行其onDraw
方法,并将Canvas obj传递给{ {1}}方法。
无法在View的onDraw中调用Canvas的方法,也无法使用onDraw
来调用View中的属性,可以保证Canvas obj是正确的。
示例代码如下:
self
错误提示:
ViewGroup = {
childcount = 0,
childs = {} -- view object list
}
function ViewGroup:onDraw(canvas)
for i=1,self.childcount do
local childView = self.childs[i]
childView:onDraw(canvas)
end
end
View = {
x = 0,
y = 0,
width = 0,
height = 0,
onDraw = nil
}
function View:new()
local o = {
onDraw = nil
}
setmetatable(o, self)
self.__index = self
return o
end
button1 = View:new()
button1.onDraw = function(canvas)
-- the problem is here, can not call Canvas's method and can not call self.width
canvas:save()
canvas:fillRect(0, 0, self.width, self.height)
canvas:restore()
end
答案 0 :(得分:4)
您使用点(.
)语法声明回调:
button1.onDraw = function(canvas)
但是你用冒号(:
)来调用它:
childView:onDraw(canvas)
第二个调用约定意味着第一个传递的参数将是self
,或者,在您的特定情况下,它等同于:
childView.onDraw(childView, canvas)
要解决此问题,请更改按钮的onDraw
以使用:
:
function button1:onDraw(canvas)
或者手动添加self
参数,就像Egor建议的那样:
button1.onDraw = function(self, canvas)