Corona SDK 程式設計教學:Segmented Control 和 Slider

PUBLISHED ON NOV 6, 2018 — 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,
      }
    )