Thursday, July 30, 2015

UIActivityIndicatorView - Show an Activity Indicator Programmatically

Update: July 8, 2017 (Swift 3.1 + Xcode 8.3.3)
Original Post: July 30, 2015 (Swift 1 + Xcode 6.4)

Complete the code as below:

Update: July 8, 2017 (Swift 3.1 + Xcode 8.3.3)

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let myActivityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
        myActivityIndicator.center = view.center
        myActivityIndicator.startAnimating()
        view.addSubview(myActivityIndicator)
    }

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

}

Original Post: July 30, 2015 (Swift 1 + Xcode 6.4)

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        var myActivityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
        myActivityIndicator.center = view.center
        myActivityIndicator.startAnimating()
        view.addSubview(myActivityIndicator)
    }

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

}

The result:

Saturday, July 4, 2015

Create an app with three tabs using the storyboard

This tutorial shows how to create tab bar items with custom icons using the storyboard.

1. Create a new project and select iOS/Application/Tabbed Application template:



2. Create a new file named ThirdViewController.swift and change the content as:

import UIKit

class ThirdViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }

}

3. Drag a ViewController to the storyboard. Select the new ViewController and make it as a ThirdViewController class in the Identity Inspector.


4. Drag a label to ThirdViewController in the storyboard. Drag it to the center. Select 'Align' at the bottom right of the interface builder, click for both horizontal and vertical center in container, and select Add 2 Constraints.


5. Control-drag from the Tab Bar Controller to the Third View Controller. Select Relationship Segue/view controllers.


6. Now the Third View Controller is renamed as Item. Select it. Change  Attributes Inspector/View Controller/Title as Third.


7. Select Item under Third/View and change Attributes Inspector/Bar Item/Title as Third.


8. Select 'Preview' as a tool to make three icons with transparent background. Make the size of the icons as 25x25 with BatchImageResizerLite. Drag the icons to the project:


9. Select Tab Bar Item under  First View Controller Scene/First View Controller/View and select an image under Attributes Inspector/Bar Item/Image.
Repeat this process for the Tab Bar Items inside the Second and Third Scenes.


10. Run the app. Try tap on 1, 2, and 3.



Wednesday, July 1, 2015

Display a web page with UIWebView and insert a JavaScript file using stringByEvaluatingJavaScriptFromString

This is a tutorial about inserting JavaScript code into the web page being read.

1. Select the storyboard and disable the Use Auto Layout and Use Size Classes option.


2. Drag a UIWebView to the storyboard.


3. Control-drag the UIWebView to ViewControl.swift

    @IBOutlet weak var myWebView: UIWebView!

4. Create an index.html file in the project:

<HTML>
    <HEAD>
        <TITLE>My Title</TITLE>
    </HEAD>
    <BODY>
        <H2><CENTER>Hello World</CENTER></H2>
    </BODY>
</HTML>

5. Create a JavaScript.js file in the project:


alert('JavaScript!');

6. Complete the ViewController.swift file as below:

import UIKit

class ViewController: UIViewController, UIWebViewDelegate {

    @IBOutlet weak var myWebView: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        var myPath = NSBundle.mainBundle().pathForResource("index", ofType: "html")
        myWebView.delegate = self //For webViewDidFinishLoad to be called
        myWebView.loadRequest(NSURLRequest(URL: NSURL(string: myPath!)!))
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        let jsPath = NSBundle.mainBundle().pathForResource("JavaScript", ofType: "js")
        let jsContent = NSString(contentsOfFile: jsPath!, encoding: NSUTF8StringEncoding, error: nil) as! String
        
        myWebView.stringByEvaluatingJavaScriptFromString(jsContent)
    }

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

}

7. The alert window:

The HTML file is displayed in UIWebView:


Thursday, June 25, 2015

UIPanGestureRecognizer - Moving a ball(UIImage) with the pan gesture programmatically

Update: July 8, 2017 (Swift 3.1 + Xcode 8.3.3)
Update: July 18, 2016 (Swift 2.2 + Xcode 7.3.1)
Original Post: June 25, 2015

1. Add an image file named ball.png to the project. 

2. Modify your ViewController.swift as below by enabling either Method 1 or Method 2.

Update: July 8, 2017 (Swift 3.1 + Xcode 8.3.3)


import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let myImageView = UIImageView(image: UIImage(named: "ball.png"))
        myImageView.frame = CGRect(x: 100, y: 100, width: 50, height: 50)
        
        myImageView.isUserInteractionEnabled = true
        //Must be enabled for tap events
        
        view.addSubview(myImageView)
        //Add an image programmatically
        
        let myPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(myPanAction)//Update: July 18, 2016 for Xcode 7.3.1(Swift 2.2)
        
        myPanGestureRecognizer.minimumNumberOfTouches = 1
        myPanGestureRecognizer.maximumNumberOfTouches = 1
        
        myImageView.addGestureRecognizer(myPanGestureRecognizer)
    }
    
    //Method 1:
    /*func myPanAction(recognizer: UIPanGestureRecognizer) {
        let translation = recognizer.translation(in: self.view)
            if let myView = recognizer.view {
            myView.center = CGPoint(x: myView.center.x + translation.x, y: myView.center.y + translation.y)
        }
            recognizer.setTranslation(CGPoint(x: 0, y: 0), in: self.view)
    }*/
    
    //Method 2:
    func myPanAction(recognizer: UIPanGestureRecognizer) {
        if ((recognizer.state != UIGestureRecognizerState.ended&&
            (recognizer.state != UIGestureRecognizerState.failed)) {
            recognizer.view?.center = recognizer.location(in: recognizer.view?.superview)
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

Update: July 18, 2016 (Swift 2.2 + Xcode 7.3.1)

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let myImageView = UIImageView(image: UIImage(named: "ball.png"))
        myImageView.frame = CGRect(x: 100, y: 100, width: 50, height: 50)
        
        myImageView.userInteractionEnabled = true
        //Must be enabled for tap events
        
        view.addSubview(myImageView)
        //Add an image programmatically
        
        let myPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(myPanAction)) //Update: July 18, 2016 for Xcode 7.3.1(Swift 2.2)
        
        myPanGestureRecognizer.minimumNumberOfTouches = 1
        myPanGestureRecognizer.maximumNumberOfTouches = 1
        
        myImageView.addGestureRecognizer(myPanGestureRecognizer)
    }
    
    //Method 1:
    /*func myPanAction(recognizer: UIPanGestureRecognizer) {
        let translation = recognizer.translationInView(self.view)
        if let myView = recognizer.view {
            myView.center = CGPoint(x: myView.center.x + translation.x, y: myView.center.y + translation.y)
        }
        recognizer.setTranslation(CGPointZero, inView: self.view)
    } */
    
    //Method 2:
    func myPanAction(recognizer: UIPanGestureRecognizer) {
        if ((recognizer.state != UIGestureRecognizerState.Ended) &&
        (recognizer.state != UIGestureRecognizerState.Failed)) {
            recognizer.view?.center = recognizer.locationInView(recognizer.view?.superview)
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

Note: you may enable either Method 1 or Method 2.

3. The result:


Tuesday, June 23, 2015

UITableViewCell - Custom Prototype Cell in UITableView with the storyboard

This is a TableView Prototype Cell Tutorial.

0. Keep the default Auto Layout and Size Classes settings in the storyboard file inspector.


1. Drag a table view to the view controller of the storyboard and then drag a table view cell into the table view.

2. Select the table view cell and set the identifier in attribute inspector as myCellIdentifier.


3. Create a new file.  Select iOS/Source/Cocoa Touch Class and next. Name the class as MyTableViewCell and a subclass of UITableViewCell.

3. Go back to the storyboard. Select myCellIdentifier (formerly the table view cell). Select the identity inspector and select MyTableViewCell as the class.


4. Drag two labels into the prototype cell. Control-drag the labels into the MyTableViewCell.swift file.

    @IBOutlet weak var myLabel1: UILabel!
    @IBOutlet weak var myLabel2: UILabel!

5. In ViewController.swift, change the class type to UITableViewController:


class ViewController: UITableViewController {

6. Complete the ViewController.swift file as below:

import UIKit

class ViewController: UITableViewController {
    
    var myArray = ["AAA", "BBB", "CCC", "DDD"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

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

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myArray.count
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("myCellIdentifier", forIndexPath: indexPath) as! MyTableViewCell
            cell.myLabel1.text = myArray[indexPath.row]
            cell.myLabel2.text = "\(indexPath.row)"
        return cell
    }
}

MyTableViewCell.swift is:

import UIKit

class MyTableViewCell: UITableViewCell {

    
    @IBOutlet weak var myLabel1: UILabel!
    @IBOutlet weak var myLabel2: UILabel!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

7. Add two images to the table cell as below:

8. Add width and height constraints to the two images:


Control-drag the top image icon to the top and select "Top Space to Container Margin".
Control-drag the top image icon to the right, and control-drag the bottom image to the right and to the bottom. Select the top option each time. 

The ViewController Scene becomes:


9. Run the app and the result is:



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

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

MKMapView - Map without using the Storyboard

1. Add MapKit and CoreLocation frameworks to the project targets.



2. Complete the code as below:

import UIKit
import CoreLocation
import MapKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        var myMapView = MKMapView(frame: self.view.bounds)
        
        myMapView.mapType = MKMapType.Standard
        
        self.view.addSubview(myMapView)
    }

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


}

Monday, June 22, 2015

Draw UITableView programmatically (without using the Storyboard)

Update: May 27, 2017 - Xcode 8.3.2 (Swift 3.1)
Update: March 28, 2016 - Xcode 7.3 (Swift 2.2)

To draw a table in iOS without using the storyboard, simply create a Single View Application project and modify ViewController.swift as below:

Xcode 8.3.2 (Swift 3.1)

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
       
        let tableView = UITableView(frame: CGRect(x: 20, y: 50, width: 200, height: 400), style: UITableViewStyle.plain)
        tableView.dataSource = self
        tableView.delegate = self
        view.addSubview(tableView)
    }
   
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }
   
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "myIdentifier")
        cell.textLabel?.text = "\(indexPath.row)"
        cell.detailTextLabel?.text = "Subtitle"
       
        return cell
    }

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

Xcode 7.3 (Swift 2.2)

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let tableView = UITableView(frame: CGRectMake(20, 50, 200, 400), style: UITableViewStyle.Plain)
        tableView.dataSource = self
        tableView.delegate = self
        view.addSubview(tableView)
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "myIdentifier")
        cell.textLabel?.text = "\(indexPath.row)"
        cell.detailTextLabel?.text = "Subtitle"
        
        return cell
    }

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

}

Result:

*****************************