Tuesday, September 15, 2015

UITextField - Create a textfield programmatically

Update - July 12, 2017 -  Xcode 8.3.3 & Swift 3.1
Update - October 13, 2015
1. Change the background color for various conditions.
2. Hide the keyboard while touching outside the text field.

Edit the ViewController.swift file as:


Update - July 12, 2017 -  Xcode 8.3.3 & Swift 3.1

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {
    
    var textField : UITextField!
    var label : UILabel!
    let str : String = "You have entered: "
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //Color #1 - Initial color
        view.backgroundColor = UIColor.yellow
        
        let placeholder = NSAttributedString(string: "Enter here", attributes: [NSForegroundColorAttributeName: UIColor.lightGray])
        
        textField = UITextField(frame: CGRect(x: 50, y: 100, width: 200, height: 20))
        
        textField.attributedPlaceholder = placeholder
        textField.textColor = UIColor.black
        textField.delegate = self
        textField.borderStyle = UITextBorderStyle.roundedRect
        textField.clearsOnBeginEditing = true
        view.addSubview(textField)
        
        label = UILabel(frame: CGRect(x: 50, y: 200, width: 200, height: 20))
        label.text = str
        view.addSubview(label)
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        //Color #2 - While selecting the text field
        view.backgroundColor = UIColor.purple
    }
    
    func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        
        //Color #3 - While touching outside the textField.
        view.backgroundColor = UIColor.cyan
        
        //Hide the keyboard
        textField.resignFirstResponder()
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        
        //Display the result.
        label.text = str+textField.text!
        
        //Color #4 - After pressing the return button
        view.backgroundColor = UIColor.orange
        textField.resignFirstResponder() //Hide the keyboard
        return true
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

Update - October 13, 2015

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    var textField : UITextField!
    var label : UILabel!
    let str : String = "You have entered:"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //Color #1 - Initial color
        view.backgroundColor = UIColor.yellowColor()
        
        let placeholder = NSAttributedString(string: "Enter here", attributes: [NSForegroundColorAttributeName: UIColor.lightGrayColor()])
        
        textField = UITextField(frame: CGRectMake(50, 100, 200, 20))

        textField.attributedPlaceholder = placeholder
        textField.textColor = UIColor.blackColor()
        textField.delegate = self
        textField.borderStyle = UITextBorderStyle.RoundedRect
        textField.clearsOnBeginEditing = true
        view.addSubview(textField)
        
        label = UILabel(frame: CGRectMake(50, 200, 200, 20))
        label.text = str
        view.addSubview(label)
    }
    
    func textFieldDidBeginEditing(textField: UITextField) {
        
        //Color #2 - While selecting the text field
        view.backgroundColorUIColor.purpleColor()
    }
    
    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        
        //Color #3 - While touching outside the textField.
        view.backgroundColor = UIColor.cyanColor()
        
        //Hide the keyboard
        textField.resignFirstResponder()
    }

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        
        //Display the result.
        label.text = str+textField.text
        
        //Color #4 - After pressing the return button
        view.backgroundColorUIColor.orangeColor()
        
        textField.resignFirstResponder() //Hide the keyboard
        return true
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

While editing the text field:



The result after hitting the return key:


UITableViewCell - Create Custom Prototype Table Cell in UITableView Programmatically (without using the Storyboard)

Update: July 13, 2017 - Xcode 8.3.3 + Swift 3.1
Original Post: September 15, 2015
===============

Update: July 13, 2017 - Xcode 8.3.3 + Swift 3.1

1. Create a new file called MyTableViewCell.swift as:


import UIKit

class MyTableViewCell: UITableViewCell {
    
    var myLabel1: UILabel!
    var myLabel2: UILabel!
    var myButton1 : UIButton!
    var myButton2 : UIButton!
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:)")
    }
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        let gap : CGFloat = 10
        let labelHeight: CGFloat = 30
        let labelWidth: CGFloat = 150
        let lineGap : CGFloat = 5
        let label2Y : CGFloat = gap + labelHeight + lineGap
        let imageSize : CGFloat = 30
        
        myLabel1 = UILabel()
        myLabel1.frame = CGRect(x: gap, y: gap, width: labelWidth, height: labelHeight)
        myLabel1.textColor = UIColor.black
        contentView.addSubview(myLabel1)
        
        myLabel2 = UILabel()
        myLabel2.frame = CGRect(x: gap, y: label2Y, width: labelWidth, height: labelHeight)
        myLabel2.textColor = UIColor.black
        contentView.addSubview(myLabel2)
        
        myButton1 = UIButton()
        myButton1.frame = CGRect(x: bounds.width-imageSize - gap, y: gap, width: imageSize, height: imageSize)
        myButton1.setImage(UIImage(named: "browser.png"), for: UIControlState.normal)
        contentView.addSubview(myButton1)
        
        myButton2 = UIButton()
        myButton2.frame = CGRect(x: bounds.width-imageSize - gap, y: label2Y, width: imageSize, height: imageSize)
        myButton2.setImage(UIImage(named: "telephone.png"), for: UIControlState.normal)
        contentView.addSubview(myButton2)
    }

}


2. Modify ViewController.swift as:


import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    var myArray = ["AAA", "BBB", "CCC", "DDD"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let tableView = UITableView(frame: view.bounds, style: UITableViewStyle.grouped)
        tableView.delegate = self
        tableView.dataSource = self
        view.addSubview(tableView)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 85
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = MyTableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "myIdentifier")
        cell.myLabel1.text = myArray[indexPath.row]
        cell.myLabel2.text = "\(indexPath.row)"
        cell.myButton1.addTarget(self, action: #selector(pressedBrowser(sender: )), for: UIControlEvents.touchUpInside)
        cell.myButton2.addTarget(self, action: #selector(pressedTelephone(sender: )), for: UIControlEvents.touchUpInside)
        return cell
    }
    
    func pressedBrowser(sender: UIButton) {
        print("pressedBrowser")
    }
    
    func pressedTelephone(sender: UIButton) {
        print("pressedTelephone")
    }
}
3. The result is:



Original Post: September 15, 2015


1. Create a new file called MyTableViewCell.swift as:

import UIKit

class MyTableViewCell: UITableViewCell {

    var myLabel1: UILabel!
    var myLabel2: UILabel!
    var myButton1 : UIButton!
    var myButton2 : UIButton!
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:)")
    }

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        let gap : CGFloat = 10
        let labelHeight: CGFloat = 30
        let labelWidth: CGFloat = 150
        let lineGap : CGFloat = 5
        let label2Y : CGFloat = gap + labelHeight + lineGap
        let imageSize : CGFloat = 30
        
        myLabel1 = UILabel()
        myLabel1.frame = CGRectMake(gap, gap, labelWidth, labelHeight)
        myLabel1.textColor = UIColor.blackColor()
        contentView.addSubview(myLabel1)
        
        myLabel2 = UILabel()
        myLabel2.frame = CGRectMake(gap, label2Y, labelWidth, labelHeight)
        myLabel2.textColor = UIColor.blackColor()
        contentView.addSubview(myLabel2)
        
        myButton1 = UIButton()
        myButton1.frame = CGRectMake(bounds.width-imageSize - gap, gap, imageSize, imageSize)
        myButton1.setImage(UIImage(named: "browser.png"), forState: UIControlState.Normal)
        contentView.addSubview(myButton1)
        
        myButton2 = UIButton()
        myButton2.frame = CGRectMake(bounds.width-imageSize - gap, label2Y, imageSize, imageSize)
        myButton2.setImage(UIImage(named: "telephone.png"), forState: UIControlState.Normal)
        contentView.addSubview(myButton2)
    }

}

2. Modify ViewController.swift as:

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    var myArray = ["AAA", "BBB", "CCC", "DDD"]

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let tableView = UITableView(frame: view.bounds, style: UITableViewStyle.Grouped)
        tableView.delegate = self
        tableView.dataSource = self
        view.addSubview(tableView)
    }

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

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 85
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myArray.count
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        var cell = MyTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "myIdentifier")
        cell.myLabel1.text = myArray[indexPath.row]
        cell.myLabel2.text = "\(indexPath.row)"
        cell.myButton1.addTarget(self, action: "pressedBrowser:", forControlEvents: UIControlEvents.TouchUpInside)
        cell.myButton2.addTarget(self, action: "pressedTelephone:", forControlEvents: UIControlEvents.TouchUpInside)
        return cell
    }

    func pressedBrowser(sender: UIButton) {
        println("pressedBrowser")
    }
    
    func pressedTelephone(sender: UIButton) {
        println("pressedTelephone")
    }
}

3. The result is:


========================================


Saturday, September 12, 2015

Print out JSON content in Swift playground

Update - May 19, 2017 Swift 3.1 (Xcode 8.3.2)
Original post - September 12, 2015 Swift 1.2 (Xcode 6.4).

1. In the playground, press 'command ⌘' + 1 to show the project navigator.
You may also do this by selecting
View -> Navigators -> Show Project Navigator.




To hide the project navigator later, press 'command ⌘' + 0.

2. Add a new file called json.txt to the Resources folder.



3.  Edit json.txt as:


{"result":{"information":[{"name":"Tom","age":25},{"name":"Andy","age":30},{"name":"Peter","age":35},{"name":"David","age":40}]}}

4.  Edit the playground as:

Update - May 19, 2017 Swift 3.1 (Xcode 8.3.2)

import UIKit

let bundle = Bundle.main
let path = bundle.path(forResource: "json", ofType: "txt")

let jsonString = try NSString(contentsOfFile: path!, encoding: String.Encoding.utf8.rawValue)

print(jsonString)

let data = jsonString.data(using: String.Encoding.utf8.rawValue)!

let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: Any]

print(json!)

let result = json?["result"] as? [String: Any]
let information = result?["information"] as? [[String: Any]]
let item = information?[0]
let name = item?["name"]
let age = item?["age"]
print(name!)
print(age!)

var array : [String] = []

for loopitem in information! {
    
    let myName = loopitem["name"]
    let myAge = loopitem["age"]
    print("name: \(myName!) age: \(myAge!)")
    array.append(String(stringInterpolationSegment: myName!))
}
for element in array {
    print("element: \(element)")
}

Original Post: September 12, 2015 with Swift 1.2 (Xcode 6.4).

import UIKit

let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("json", ofType: "txt")
let jsonString = NSString(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)!
println(jsonString)

var data : NSData! = jsonString.dataUsingEncoding(NSUTF8StringEncoding)

let json:AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error:nil)
println(json)

let result: AnyObject? = json["result"]
let information: AnyObject? = result?["information"]
let item : AnyObject? = information?[0]
let name: AnyObject? = item?["name"]
let age: AnyObject? = item?["age"]
println(name!)
println(age!)

var array : [String] = []

for loopitem in result?["information"] as! NSArray {
    
    let myName: AnyObject? = loopitem["name"]
    let myAge: AnyObject? = loopitem["age"]
    println("name: \(myName!) age: \(myAge!)")
    array.append(String(stringInterpolationSegment: myName!))
}
for element in array {
    println("element: \(element)")
}

5. The result is:



Related Information:

JavaScript and JSON