Your First Swift 4 & iOS 12 App Online Course – Day 4

Day 4

 

Getting the value of slider and printing it in the Alert Box

 

  • Initialize a global variable currentValue of type Int and assign it the default value of 50.
  • Inside the sliderMoved method assign the slider.value.rounded() to the currentValue. Remember to cast slider.value.rounded() as we only need the integer values and not the decimal ones.
  • Copy the message inside the print statement in the sliderMoved method. Create another variable message inside showAlert() method of type string and assign the message to it. Replace slider.value in the message to currentValue.
  • Replace the old message in UIAlertController with message variable. Now run the app and change the slider position. Click Hit Me. We see the current value in the alert message.

 

Learning iOS Development Day 4 Current Value of slider in Alert Message
Current Value of slider in Alert Message

 

Connecting Outlets

 

  • Right now we can access the slider only in one method. And we want to access its current value in another method or globally. This creates a need to have an instance variable of type UISlider. We can do that by using @IBOutlet like this

 

@IBOutlet weak var slider: UISlider!

 

  • Next open Main.storyboard -> control + click on slider -> click on New Referencing outlets and connect it to ViewController which pops up two options -> select slider
  • Now copy the code in sliderMoved to viewDidLoad. This makes sure that by default the current value of the slider is taken if the user hits the button “Hit Me!” without changing the slider value.
  • By default the slider’s value id 50. So now when we run the app and click on “Hit Me” , 50 is shown.

 

Learning iOS Development Day 4 Connecting outlets
Connecting outlets