Sunday, May 24, 2015

UISlider - value adjustment

This is a simple UISlider tutorial.

1. Disable 'Use Auto Layout' in the storyboard file inspector.


2. Drag a label to the storyboard. Write the content as the initial value 50.

3. Drag a slider to the storyboard and adjust its length.

4. Select the slider and select the 'Attributes Inspector', and adjust the maximum value to 100 and the current value to 50 as below:




5. Control-drag the label to ViewController.swift:


    @IBOutlet weak var myLabel: UILabel!


6. Control-drag the slider to ViewController.swift:





    @IBAction func mySlider(sender: UISlider) {

    }

7. Complete the code as below:


import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var myLabel: UILabel!
    @IBAction func mySlider(sender: UISlider) {
        
        var myValue = Int(sender.value)
        println(myValue)
        self.myLabel.text = "\(myValue)"
    }
    override func viewDidLoad() {
        super.viewDidLoad()

    }

8. The result is:


Wednesday, May 20, 2015

arc4random() - Random Number Generator

1. Disable 'Use Auto Layout' in the storyboard file inspector.


2. Drag a label to the storyboard.

3. Drag a button to the storyboard. Make the text as "Generate".


4. Control-drag the label to ViewController.swift:

    @IBOutlet weak var myNumber: UILabel!

5. Control-drag the button to ViewController.swift and make it an IBAction:

    @IBAction func btnGenerate(sender: AnyObject) {

    }

6. Complete the code as below:


import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var myNumber: UILabel!
    @IBAction func btnGenerate(sender: AnyObject) {
        
        var myGeneratedNumber = arc4random() % 100
        self.myNumber.text = "\(myGeneratedNumber)"
    }

    override func viewDidLoad() {
        super.viewDidLoad()

    }

7. The result is: