iOS Tutorial: TextField Delegate Usage (Swift + Xcode)

This entry is part 32 of 32 in the series iOS Apps

Quick example of how to use the TextFieldDelegate protocol
Limit the number of characters a user can enter
Dismiss keyboard

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {


    @IBOutlet weak var mTextField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        mTextField.delegate = self
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
        print("Allow editing")
        return true
    }
    
    func textFieldDidBeginEditing(textField: UITextField) {
        print("Begin Editing")
    }
    
    func textFieldDidEndEditing(textField: UITextField) {
        print("Editing is done")
    }
    
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        print("Enter was pressed")
        textField.resignFirstResponder()
        return true
    }
    
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        
        let length = (textField.text?.characters.count)! + string.characters.count
        
        if length > 10 {
            return false
        } else {
            return true
        }
    }
    
    func textFieldShouldClear(textField: UITextField) -> Bool {
        print("Clear pressed")
        return true
    }
    
}

 

Collection View with Animations

This entry is part 30 of 32 in the series iOS Apps

Collections View Animations – Swift with Xcode.

ViewController.swift

import UIKit

class ViewController: UICollectionViewController {
    
    var imagesArray = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        imagesArray = ["light","light1","light2","light3"]
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath)
        
        let imageView = cell.viewWithTag(1) as! UIImageView
        
        imageView.image = UIImage(named: imagesArray[indexPath.row])
        
        let backBtn = cell.viewWithTag(3) as! UIButton
        backBtn.hidden = true
        
        return cell
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return imagesArray.count
        
    }
    
    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let cell = collectionView.cellForItemAtIndexPath(indexPath)
        cell?.superview?.bringSubviewToFront(cell!)
        
        UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: UIViewAnimationOptions.TransitionNone, animations: ({
            
            cell?.frame = collectionView.bounds
            collectionView.scrollEnabled = false
            let backBtn = cell!.viewWithTag(3) as! UIButton
            backBtn.hidden = false
            
        }), completion: nil)
    }
    
    
    @IBAction func bkBtnAction(sender: UIButton) {
        let indexPath = collectionView?.indexPathsForSelectedItems()
        collectionView?.scrollEnabled = true
        collectionView?.reloadItemsAtIndexPaths(indexPath!)
    }
}

 

How to read JSON using Swift 2.0

This entry is part 29 of 32 in the series iOS Apps

ViewController.swift

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        guard let path = NSBundle.mainBundle().pathForResource("test", ofType: "json") else {
            print("Error finding file")
            return
        }

        do {
            let data: NSData? = NSData(contentsOfFile: path)
            if let jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
                let dataDictionary = jsonResult["list"] as! NSDictionary
                let total = dataDictionary["total"]
                print("total items : \(total!)");
                let itemArray = dataDictionary["item"] as! NSArray
                for item in itemArray {
                    let group = item["group"]!
                    let offset = item["offset"]!
                    let name = item["name"]!
                    let ndbno = item["ndbno"]!
                    print("Item \(offset!): \(group!) - \(name!) - \(ndbno!)")
                }
            }
        } catch let error as NSError {
            print("Error:\n \(error)")
            return
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}