Mert Karakas
Mert Karakas

Reputation: 178

Swift 3: Using a slider to show time

I am trying to write an alarm clock like the new Bedtime feature of IOS 10 but I am fairly new to Swift. I have 2 UISliders: one is for when to sleep and the other when to wake up. My question is: How can I combine the two UISliders? and how can I make it count minutes and hours? Is it possible to have gridlines and stop points in the slider? My idea is to have increments of 0.12 and whenever the value reaches 0.60, I would count it as 1 hour and "..." minutes.

EDIT: Added image and code

import UIKit
class ViewController: UIViewController {
    @IBOutlet weak var sleepTime: UISlider!
    @IBOutlet weak var displaySleep: UITextField!
    var sliderValue1 = 12
    var sliderValue2 = 12
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    @IBAction func slider1Changed(_ sender: UISlider!) {
        var currentValue1 = Int(sender.value)
        displaySleep.text = "\(sliderValue2 - currentValue1) hours of sleep"
    }
    @IBAction func slider2Changed(_ sender: UISlider!) {
        var currentValue2 = Int(sender.value)
        displaySleep.text = "\(currentValue2 - sliderValue1) hours of sleep"
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

enter image description here

Upvotes: 0

Views: 1165

Answers (1)

dispatchswift
dispatchswift

Reputation: 1056

To answer your first question.

You can combine the two sliders by utilizing a Segmented Control. When the user selects either "Sleep" or "Wake Up" it will change the Slider values accordingly upon implementation.

Control click then drag from your segmented control to your View Controller class to create a IBAction connection. Make sure to change the type to UISegmentedControl.

  @IBAction func onControlChanged(_ sender: UISegmentedControl) {
    switch sender.selectedSegmentIndex {
    case 0: // Sleep selected
      // Update Slider 
      break

    case 1: // Wake Up selected
      // Update Slider
      break

    default: 
      break
    }
  }

enter image description here

Upvotes: 1

Related Questions