Corona SDK ScrollView滚动量为触发元素

时间:2015-03-01 20:18:40

标签: function lua scrollview corona corona-storyboard

我有一个"逻辑"问题的类型,我正在使用Corona SDK。

我正在使用ScrollView小部件,并想知道我是否可以创建一个函数或某些东西来设置" y"滚动到或过去时触发的元素(顶部导航栏)根据滚动方向淡入或淡出的数量。

举个例子:

你有ScrollView,向下滚动(y)30px。该元素位于alpha = 0并开始淡入,当您达到40px它alpha = 1时。向上滚动但相反,alpha = 1为40px,alpha = 0为30px。

当你滚动设置" y"当我可以让元素(顶部导航栏)淡入或淡出时,这将是很好的。从任何一个方向而不是一次全部。因此,如果您只滚动35px,则元素位于alpha = 5

enter image description here

1 个答案:

答案 0 :(得分:1)

这取自Corona SDK示例:

local widget = require( "widget" )

-- ScrollView listener
local function scrollListener( event )

    local phase = event.phase
    if ( phase == "began" ) then print( "Scroll view was touched" )
    elseif ( phase == "moved" ) then print( "Scroll view was moved" )
    elseif ( phase == "ended" ) then print( "Scroll view was released" )
    end

    -- In the event a scroll limit is reached...
    if ( event.limitReached ) then
        if ( event.direction == "up" ) then print( "Reached top limit" )
        elseif ( event.direction == "down" ) then print( "Reached bottom limit" )
        elseif ( event.direction == "left" ) then print( "Reached left limit" )
        elseif ( event.direction == "right" ) then print( "Reached right limit" )
        end
    end

    return true
end

-- Create the widget
local scrollView = widget.newScrollView
{
    top = 100,
    left = 10,
    width = 300,
    height = 400,
    scrollWidth = 600,
    scrollHeight = 800,
    listener = scrollListener
}

-- Create a image and insert it into the scroll view
local background = display.newRect(160, 240, 320, 480)-- display.newImageRect( "assets/scrollimage.png", 768, 1024 )
background:setFillColor(1, 0, 0)
scrollView:insert( background )

你可以看到scrollview小部件有其他事件可以达到它的限制。

local widget = require( "widget" )

-- ScrollView listener
local function scrollListener( event )
    if event.phase == "moved" then
        local x, y = event.target:getContentPosition()
        if y > 40 then 
            print("****")
        end 
    end 
    return true
end

这是一个简化的例子。这里我使用:getContentPosition()返回scrollview的x和y位置

向下滚动滚动视图内容向上移动时,y位置将为负数。对于拉动刷新,您可能会寻找正数,滚动视图会被拉到其容器的顶部边缘下方。要查找scrollview中的内容何时接近scrollview容器的顶部,您需要查找负数。

这是一个定义0,-40和-80像素的某些路点的示例。它会在达到新的航点时打印航点的索引。

local waypoints = {0, -40, -80}
local currentWayPoint = 0

-- ScrollView listener
local function scrollListener( event )
   if event.phase == "moved" then
        local x, y = event.target:getContentPosition()
        local newWayPoint = -1
        for i = 1, #waypoints do 
            local waypoint = waypoints[i]
            -- print(waypoint, y, i)
            if waypoint > y then
                newWayPoint = i
            end 
        end 
        if newWayPoint ~= currentWayPoint then 
            currentWayPoint = newWayPoint
            print( currentWayPoint )
        end 
    end 
    return true
end

此处,如果向下拖动,终端应显示-1,然后在向上拖动每个路径值(每40个像素)时显示1,2和3。您可以添加if语句来检查航点值是否发生变化,然后执行某些操作。