ud788 ยป

Lesson 3 Code Reference Sheet

This outline is intended as a quick way to reference code snippets. It includes any code you were expected to write yourself and git branch names for code provided for you.

Compare and Contrast Textfields

git clone <clone_url>
git checkout <branchName>

In this case:
git clone https://github.com/udacity/ios-nanodegree-uikit.git
git checkout step3.1-textFieldsApp

Creating a Random Color Delegate

In the RandomColorTextFieldDelegate. swift file:

// Step 2. Import UIKit
import UIKit

// Step 3. Define class, subclass NSObject, and declare UITextFieldDelegate protocol 
class RandomColorTextFieldDelegate: NSObject, UITextFieldDelegate {
//Step 4. Create a method that will return a random color
func randomColor() {
    //TODO: Implement to return a random color of class UIColor()
}
// Step 5: Implement textFieldShouldChangeCharactersInRange, set the color of your text
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    textField.textColor = self.randomColor()
    return true
}

In the ViewController.swift file:

// Step 1. Add a variable for the new delegate.
let randomColorDelegate = RandomColorTextFieldDelegate()
//Step 2. Assign the delegate to textField2
override func viewDidLoad() {
    super.viewDidLoad()

    // Set the three delegates
    self.textField1.delegate = emojiDelegate       
    self.textField2.delegate = randomColorDelegate // Here is Step 2 
    self.textField3.delegate = self
}

Random Color Delegate Code

One way to write a method which will generate a random color.
From RandomColorTextFieldDelegate.swift:

class RandomColorTextFieldDelegate: NSObject, UITextFieldDelegate {
     // Here we create an array of colors    
     let colors = [UIColor.redColor(),
      UIColor.orangeColor(), UIColor.yellowColor(),
      UIColor.greenColor(), UIColor.blueColor(),
      UIColor.purpleColor(), UIColor.brownColor()];

      // Then we choose a random number. 
      func randomColor() -> UIColor {
          let randomIndex = Int(arc4random()) % colors.count

         // We get a color from the colors array using the random number as an index
         return colors[randomIndex]
      }    

    // The color of the text in the textField is set to the randomly chosen color.
    func textField(textField: UITextField,     shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        textField.textColor = self.randomColor()        
        return true
    }    
}

Preparing for the Challenge Apps

//Casting a Swift string to an NSString 
var newText = textField.text as NSString

// NSString method, stringByReplacingCharactersInRange
newText = newText.stringByReplacingCharactersInRange(range, withString: string)

Challenge Apps

To access the sample solution:

git checkout step3.2-textFieldsChallengeApp-solution