【在主画面加入捷径】
       
【选择语系】
繁中 简中

Corona SDK 程序设计教学:Segmented Control 和 Slider

MOBILE
【赞助商连结】

    本文会展示 segmented control 和 slider 两种元件。Segmented control 可在数种状态间切换,概念上类似 Switch,但类更多。Slider 则可用来做细微的数值调控。我们将范例放在这里,本文仅节录部分内容。

    程序的示意图如下:

    Corona SDK 的 segmented control 和 slider

    本范例的元件会调整背景颜色,所以我们把这个功能独立成一个函式,后续程序就可藉由调用此函式来调整背景颜色:

    -- Init the parameters related to background color.
    local red = 245
    local green = 245
    local blue = 220
    local factor = 1
    
    -- Declare the function to set background color.
    local function setBackground(r, g, b, f)
      display.setDefault("background", r * f / 255, g * f / 255, b * f / 255)
    end
    
    -- Set initial background color.
    setBackground(red, green, blue, factor)
    

    接着,我们撰写 segmentedControl 物件。这个物件分为三类,分别对应不同颜色的背景。程序会由 target.segmentNumber 来得知目前选择那一个子项目,程序就会据此改变背景颜色:

    -- Declare the listener for Segmented Control object.
    local function onSegmentPress(event)
      local target = event.target
    
      if target.segmentNumber == 1 then
        -- Set RGB color to beige.
        red = 245
        green = 245
        blue = 220
      elseif target.segmentNumber == 2 then
        -- Set RGB color to skyblue.
        red = 135
        green = 206
        blue = 235
      elseif target.segmentNumber == 3 then
        -- Set RGB color lightgreen.
        red = 144
        green = 238
        blue = 144
      end
    
      setBackground(red, green, blue, factor)
    end
    
    -- Init a Segmented Control object.
    local segmentedControl = widget.newSegmentedControl(
      {
        x = display.contentCenterX,
        y = display.contentHeight * 0.38,
        segmentWidth = 80,
        segments = { "Beige", "Sky Blue", "Light Green"},
        defaultSegment = 1,
        onPress = onSegmentPress
      }
    )
    

    在本范例的 slider 物件中,当 event.value 越大时,factor 会越小,藉此调整背景的亮暗度:

    -- Declare the listener for Slider object.
    local function sliderListener(event)
      if event.phase == "moved" then
        factor = ((100 - event.value) * 0.2 + 80) / 100
        setBackground(red, green, blue, factor)
      end
    end
    
    -- Init a Slider object.
    local slider = widget.newSlider(
      {
        x = display.contentCenterX,
        y = display.contentHeight * 0.47,
        width = display.contentWidth * 0.75,
        value = 0,
        listener = sliderListener,
      }
    )
    
    【赞助商连结】