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:


No comments:

Post a Comment