• Skip to main content
  • Skip to primary sidebar

Ravi Shankar

Tweaking Apps

  • About
  • Portfolio
  • Privacy Policy

ios

PDFKit – View, Annotate PDF file in Swift

April 10, 2020 By Ravi Shankar 1 Comment

In this demo, we will be using PDFKit to View and Annotate PDF file. Let us start by selecting a Single View App template and name the project as PDFDemo.

For this demo, we will be using a PDF file “TheWakingLights.pdf” and this can downloaded from the github project folder. Now drag and drop this file to Xcode project and in “Choose options for adding these files” select “Copy items if needed”

Displaying PDF

In Xcode’s project navigator, select ViewController.swift and add the following lines after viewDidLoad function.

  
            func openPDFDocument() {   
                guard let path = Bundle.main.url(forResource: "TheWakingLights",                        withExtension: "pdf")
                else { 
                 return     
                }      
                let document = PDFDocument(url: path)   
                let pdfView = PDFView(frame: view.frame)     
                pdfView.document = document       
                view.addSubview(pdfView)  

This function does the following

   guard let path = Bundle.main.url(forResource: "TheWakingLights",
                                         withExtension: "pdf") else { return }

Creates URL instance with the path of “TheWalkingLights.pdf” file.

Loads the pdf file in a PDFDocument object

 let document = PDFDocument(url: path)

Creates an instance of PDFView and sets the frame to ViewController’s view then assigns the PDFDocument to PDFView instance.

        let pdfView = PDFView(frame: view.frame)
        pdfView.document = document
        view.addSubview(pdfView)

You will be seeing couple of unresolved identified errors because of missing import PDFKit statement. Add import statement after import UIKit and now you should be able to run the app on the simulator and select text on the PDF

select text

Adding Annotation to PDF

PDFKit provides option to add annotation to PDF file using PDFAnnoation class. Various annotation can be added like Circle, line, Strikeout, Square, Underline, Highlight etc.. Let us see a code example of adding highlight to PDF page.

Add the following code snippet after openPDFDocument function.

  func highlightAnnotation() -> PDFAnnotation {
        let annotation = PDFAnnotation(bounds: CGRect(x: 30, y: 80, width: 230, height: 50),
                                       forType: .highlight, withProperties: nil)
        annotation.color = .yellow
        return annotation
    }

The above code does the following

  1. Creates a PDFAnnotation instance by specifying coordinates for adding the annotation and setting the type of annotation to highlight.
  2.  Then the annotation colour is set to yellow.

In the openDocument function add the following line after view.addSubView(pdfview)

   pdfView.currentPage?.addAnnotation(highlightAnnotation())

This gets the current page from PDFView and sets the highlight annotation. When you run the app on the simulation you will see the highlight as shown below.

final

Download the source code from here

 

Filed Under: ios, Swift Tagged With: Annotation, PDFDocument, PDFKit, Swift

Swift – WebView demo

November 6, 2019 By Ravi Shankar 24 Comments

Updated for Swift 5

In this short tutorial, we will see an example in Swift programming language using UIWebView. The WebView will load a webpage and provide option to refresh, stop, go back and go forward. This tutorial should give a brief overview on how to declare IBAction, IBOutlets and use Objective-C classes (NSURL and NSURLRequest) in Swift


Interface Design

Step 1: Create a Single View Application Project and make sure to select the programming language as Swift

Choose Swift Language in Xcode

Step 2: Select Main.Storyboard under Project navigator. then drag and drop WebView and Toolbar from Object Library to the View Controller.

Step 3: Now place four bar button items on Toolbar to provide stop, refresh, go back and go forward functionality. You can also use flexible and fixed separators for aligning the bar button items.

Use Suggested Constraints in Xcode 6

Step 4: Make sure to use the SuggestedConstraints for WebView and Toolbar. You can do this by selecting the controls and using the Reset to Suggested Constraints available as part of Resolve Auto Layout option. This would ensure that the controls gets adjusted automatically depending upon the device’s screen width and height.

Reset to Suggested Constraints

Updated – 28/08/2014

Since some users are facing problems with Reset to Suggested Constraints in Xcode 6 Beta 6, you can use Pin option to define the four constraints using the default values. Then click Add 4 Constraints available at the bottom of the screen.

201408281213.jpg

Write Code

Step 5: Navigate to ViewController.swift file on the Project Navigator. Add the following line after class ViewController: UIViewController which defines the IBOutlet element for WebView.

@IBOutlet var webView: UIWebView!

Then connect this IBOutlet element to the WebView on InterfaceBuilder.

Step 6: In the viewDidLoad function, create URL and NSURLRequest for the webpage and associate this with the WebView by calling loadRequest method.

override func viewDidLoad() 
{   
  super.viewDidLoad() 
  let url = NSURL(string: "https://rshankar.com")
  let request = NSURLRequest(url: url! as URL)       
  webView.delegate = self
  activityIndicator.hidesWhenStopped = true
  activityIndicator.startAnimating()
  webView.loadRequest(request as URLRequest) 
}

Step 7: Now add the corresponding IBAction methods for the four buttons stop, refresh, go back and go forward. And connect these IBActions to the buttons on Interface builder.

func webViewDidFinishLoad(_ webView: UIWebView) 
{ 
      activityIndicator.stopAnimating()   
}                                                                                           

@IBAction func doRefresh(_: AnyObject) {                                                              
  webView.reload()
}

@IBAction func goBack(_: AnyObject) 
{   
   webView.goBack()    
}

@IBAction func goForward(_: AnyObject) {
  webView.goForward()
}

@IBAction func stop(_: AnyObject) 
{
   webView.stopLoading()
}

Step 8: Compile and run the project by selecting a suitable simulator.

Download the souce code from GitHub.

Filed Under: ios, Programming, Xcode Tagged With: Swift, WebView, Xcode

Assertions supported in XCTest

March 23, 2017 By Ravi Shankar Leave a Comment

Here you can find the list of Assertions supported by XCTest and it is essential to know all these assertion if you are practicing Test Driven Development in IOS. You can get this list from XCTestAssertions.h

  • XCTFail(<#format…#>) – This unconditionally fails the test.
  • XCTAssertNil(<#a1#>, <#format…#>) – Failure message when object is not nil.
  • XCTAssertNotNil(<#a1#>, <#format…#>) – Failure message when object is nil
  • XCTAssertEqual(<#a1#>, <#a2#>, <#format…#>) – Failure message when expressions(a1 & a2) are not equal.
  • XCTAssertNotEqual(<#a1#>, <#a2#>, <#format…#>) – Failure message when expressions(a1 & a2) are equal.
  • XCTAssertEqualObjects(<#a1#>, <#a2#>, <#format…#>) – Failure message when objects(a1 & a2) are not equal.
  • XCTAssertNotEqualObjects(<#a1#>, <#a2#>, <#format…#>) – Failure message when objects(a1 & a2) are not equal.
  • XCTAssertEqualWithAccuracy(<#a1#>, <#a2#>, <#accuracy#>, <#format…#>) – Failure message when a1 is not equal to a2 with + or – accuracy.
  • XCTAssertNotEqualWithAccuracy(<#a1#>, <#a2#>, <#accuracy#>, <#format…#>) – Failure message when a1 is equal to a2 with + or – accuracy.
  • XCTAssertNoThrow(<#expression#>, <#format…#>) – Failure message when expression does throw exception.
  • XCTAssertNoThrowSpecific(<#expression#>, <#specificException#>, <#format…#>) – Failure message when expression throws specific exception.
  • XCTAssertNoThrowSpecificNamed(<#expression#>, <#specificException#>, <#exception_name#>, <#format…#>) – Failure message when expression throws specific class with specific name.
  • XCTAssertThrows(<#expression#>, <#format…#>) – Failure message when expression does not throw exception.
  • XCTAssertThrowsSpecific(<#expression#>, <#specificException#>, <#format…#>) – Failure message when expression does not throw specific exception.
  • XCTAssert(<#expression#>, <#format…#>) – Failure message when expression is false.
  • XCTAssertTrue(<#expression#>, <#format…#>) – Failure message when expression is false.
  • XCTAssertFailure(<#expression#>, <#format…#>) – Failure message when expression is true.

Filed Under: Develop, ios, Xcode Tagged With: Assertions, Xcode, XCTest

iOS Swift – Firebase Demo

November 26, 2015 By Ravi Shankar 4 Comments

Firebase is a platform that allows web and mobile application to store data in cloud. In this article, we will see an example app written in Swift that uses Firebase for storing and retrieving data in real time. The source code for this demo is available under GitHub.

This demo app consists of three fields for capturing name, date and image. These data are then converted in to required data type for storing purpose.

Installing Firebase in iOS SDK Project

The easiest way to include Firebase SDK to your iOS project is by using Cocoapods and the instruction are clearly given in Firebase documentation section. After installing the Firebase iOS sdk make sure to create a bridge file by adding the following import statement.

[code language=”swift”]#import Firebase/Firebase.h
[/code]

Firebase DataStore

User with Google or GitHub account can directly login to Firebase. The data stored in Firebase in JSON format. Find below a screenshot of the data stored by this demo app.

Profiles is top node and under which each row is stored as key/value pairs with name as the identifier for each row. Firebase provides a path (URL ) for storing the data which ends with firebaseio.com. You should be able find this URL in Firebase main screen.

[code language=”plain”]Example :- _unique_identifier_.firebaseio.com[/code]

Saving data to Firebase

You need to create a reference to Firebase class as shown below

[code language=”swift”]let firebase = Firebase(url:”https://_unique_identifer.firebaseio.com/profiles”)[/code]

replace _unique_identifier with the identifier provided for your Firebase account.

The following piece of code is used for saving the information to Firebase.

[code language=”swift”]@IBAction func save(sender: AnyObject) {

let name = nameTextField.text
var data: NSData = NSData()

if let image = photoImageView.image {
data = UIImageJPEGRepresentation(image,0.1)!
}

let base64String = data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)

let user: NSDictionary = [“name”:name!,”dob”:dateOfBirthTimeInterval, “photoBase64”:base64String]

//add firebase child node
let profile = firebase.ref.childByAppendingPath(name!)

// Write data to Firebase
profile.setValue(user)
}
[/code]

The above code does the following

  1. Converts image to to JPEG also compresses the size as we will be storing the image as base64EncodedString. 
  2. Creates a dictionary with name, image (String data) and date (as timeinterval).
  3. This dictionary is then added to the FIrebase Datastore by appending the name as the identifier for each row.
  4. And to save the data to Firebase, you need to call profile.setValue by passing the dictionary object.

Retrieving data from Firebase

Here again you need to create a reference to Firebase class by passing the required path as shown below

[code language=”plain”]let firebase = Firebase(url:”https://_unique_identifer.firebaseio.com/profiles”[/code]

In the following price of code, firebase.observerEventType is used for retrieving the data from Firebase account. The data gets refreshed in real time when ever any updates happen in the data store. This is really cool!!!

[code language=”swift”]func loadDataFromFirebase() {

UIApplication.sharedApplication().networkActivityIndicatorVisible = true

firebase.observeEventType(.Value, withBlock: { snapshot in
var tempItems = [NSDictionary]()

for item in snapshot.children {
let child = item as! FDataSnapshot
let dict = child.value as! NSDictionary
tempItems.append(dict)
}

self.items = tempItems
self.tableView.reloadData()
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
})
}[/code]

snapshot referes to the collection of records store under a path. You can iterate through the collection to reteive each data item.

Delete a row from Firebase

[code language=”swift”]override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {

let dict = items[indexPath.row]
let name = dict[“name”] as! String

// delete data from firebase

let profile = firebase.ref.childByAppendingPath(name)
profile.removeValue()
}
}
[/code]

 

Removing a row from Firebase can be done by calling removeValue method on the Firebase object reference as shown in the above code snippet.

In this tutorial, we have seen only the code related with Firebase. You can download the full source from here

Filed Under: ios, Swift Tagged With: Cloud, Firebase

Swift – Beginners Tutorial

May 8, 2015 By Ravi Shankar Leave a Comment

Swift is the latest programming language released by Apple for developing OS X and iOS apps.

  • Best of C and Objective-C
  • Adopts safe programming patterns and modern features
  • Supports Playground, a tool for seeing the result immediately.
  • Provides access to Cocoa libraries and can work in conjunction with Objective-C
  • Combines Procedural and Object-Oriented programming.
  • No need to use semicolon at the end of statement. Use it only when you have more than one statement in single line.
  • Swift uses var and let. only mutable variable needs var.
  • Swift uses type inference.
  • Supports unicode characters. You can use any character as variable.
  • Prefer usage of constant (let) for immutable than using var.
  • Optional variables can contain value or nil. – var givenName : String? = “Ravi”
  • Swift’s Switch supports all kinds of datatype and operations and does not need a break statement after each case statement.
  • No need to enclose your expression in brackets with if statements
  • Swift function supports default value for the parameter and variable parameter.
  • Closures are like blocks in Objective-C ( ) -> ( )
  • No need to specify header file in Swift
  • No need to specify base class and there is no universal base class
  • No difference between instance variable and properties
  • Tuples – Grouping of multiple values.
  • Nested multiline comments are allowed.
  • Use typealias to provide different name to an existing type.
  • Swift nil represents absence of value and objective – C nil represents pointer to a non-existent object.
  • Implicitly unwrapped optional let pincode : String! = “E151EH”
  • Provides Assertion to end code execution where certain criteria is not met.
  • Swift’s String is value type and not passed by reference.
  • Supports Optional Binding and Optional Chaining

Variables and Constants

[code language=”swift”]
// Variables and Constants

var myStr = "Swift"
var myValue = 23.1 //(Implicit variable declaration or type inference)
var myDoubleValue: Double = 23 //(Explicit variable declaration)

// let

let myAge = 38
let message = "My age is " + String(myAge) //(Converting value to a String)
let newMessage = "My age is \(myAge)" //(Converting value to a String using backslash or interpolation)

[/code]

Data types in Swift

  • String
  • Int (Range -2,147,483,648 to 2,147,483,648)
  • Double (15 digit precision)
  • Float (6 digit precision)
  • Bool

Fun with String

[code language=”swift”]// String
var movie:String = "Independence Day "
count(movie) // count of string

// Use NSString to format a double or float value
var range = NSString(format: "%.2f", 24.5)

// Concatenate String values
movie += String(range)[/code]

 

Collection Types

Array

[code language=”swift”]// Declarations
// var fruits = ["Orange", "Apple", "Grapes"] – Short declartion
// var fruits:Array = ["Orange", "Apple", "Grapes"] – Long declaration
// var fruits:[String] = [] – Assign empty array

var fruits:[String] = ["Orange", "Apple", "Grapes"] // short declaration with type.

// insert item at index
fruits.insert("Mangoes", atIndex: 2)

// append item to the last
fruits.append("Pine Apple")

// count of array
fruits.count

// remove item
fruits.removeAtIndex(1)

// sort array elements
fruits.sort { (a, b) -&gt; Bool in
a &lt; b
}

// retrieve index using find
find(fruits, "Mangoes")
[/code]

Dictionary

[code language=”swift”]// Dicionary

// Declaration

// var employees = [1:"John",2:"Peter",3:"David"] // Short form

// var employees:Dictionary = [1:"John",2:"Peter",3:"David"] // Long form

// var employees:[Int:String] = Dictionary() // Empty dictionary

var employees:[Int:String] = [1:"John",2:"Peter",3:"David"] //Short form with type

// Add new item to dictionary

employees[4] = "Bob"

// Remove an item using key

employees.removeValueForKey(3)
[/code]

Assignment Operator

  • a = b
  • let (a,b) = (2,3) – supports tuple.
  • Does not return value.

Arithmetic Operators

  • Addition (+), Subtraction (-), Multiplication (*), Division (/)
  • + can be used for string concatenation.
  • % – Returns remainder for both +ve and -ve numbers. Also returns remainder for floating point numbers.
  • Increment and Decrement operators, ++i (i = i + 1), —i (i = i – 1).
  • Supports i++ and i— (increments or decrements after returning the value).
  • Unary Minus and Unary Plus

Compound AssignmentOperator

  • x += 2 is same as x = x + 2.

ComparisonOperators

  • x == y
  • x != y
  • x > y
  • x < y
  • x >= y
  • x <= y
  • === and !== used for testing object references.

Ternary Conditional Operator

  • a = flag ? 10 : 20 (if flag is true then a will updated to 10 and 20 incase it is false).

RangeOperators

  • Closed Range – e.g.:- 1…10, has three dots and includes values from 1 to 10.
  • Half Closed – e.g.:- 1..10, has two dots and includes values from 1 to 9

LogicalOperators

  • NOT ( !x )
  • AND ( x && y )
  • OR ( x || y )

Control Flow

[code language=”swift”]// Control flow

// if else
if fruits[0] == "Grapes" {
println("for breakfast")
} else if fruits[0] == "Apple" {
println("for lunch")
} else {
println("Nothing")
}

// for statements
// exclusive range

for index in 0..<h3><u>Comments</u></h3>[code language="swift"] Single line comments // examples
Multiline comments /* example1
example2 */

[/code]

Function

[code language=”swift”]func sum(number1:Int, number2: Int) -&gt; (Int) {
return number1 + number2
}[/code]

The above function is an example of multiple input parameters. It does the addition of two numbers where number1 and number are arguments of type Int and it returns a value of type int. And a function without parameter looks like this.

[code language=”swift”]
func sum() -&gt; (Int) {
return 10 + 5
}[/code]

The above function is an example of multiple input parameters. It does the addition of two numbers. number1 and number are arguments of type Int and it returns a value of type int. And a function without parameter looks like this. Swift function can also have multiple return values.


Define external parameter name

[code language=”swift”]func sum(addNumber1 number1:Int, withNumber2 number2: Int) -&gt; (Int) {
return number1 + number2
}

println(sum(addNumber1: 10, withNumber2: 20))
[/code]

 

addNumber1 and withNumber are external parameter names for two parameters. And you use # to tell local and external parameter name are same.

[code language=”swift”]
func sum(#number1:Int, #withNumber2: Int) -&gt; (Int) {
return number1 + withNumber2
}
println(sum(number1: 10, withNumber2: 20))[/code]

Function with default parameter value

[code language=”swift”]func sum(number1:Int, withNumber2: Int = 20) -&gt; (Int) {
return number1 + withNumber2
}
println(sum(10))[/code]

The above function has default value for the second parameter.

Variadic Parameters

 

A function with variadic parameters can accept zero or more values. Maximum of one parameter is allowed in a function and it is always last in the list.

[code language=”swift”]
// Variadic parameters
func totalSum(numbers:Int…) -&gt; Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
totalSum(1,2,3,4,5)[/code]

Variable and inout parameters

Variable parameters in a function are indicated by var keyword and the scope is available only within the function. If you want to access the modified variable value outside the function then you specify them as inout parameter. And prefix with & while passing the parameter in the function call.

[code language=”swift”]
// inout parameters
var employee = "Ravi"

func greetings(inout employee:String) {
employee += "!"
}
println(greetings(&amp;employee))
println(&amp;employee)[/code]

Filed Under: Apple, ios, Mac Tagged With: Apple, Quick Reference, Swift

Optional binding and Optional Chaining

May 7, 2015 By Ravi Shankar 6 Comments

Swift has a feature that lets users to assign optional value to a variable or a constant. Optional variable or constant can contain a value or a nil value. Let us take the following example which tries to find a given string in a array of string.

Optional Binding

[code language=”swift”]var fruits = ["Apple","Orange","Grape","Mango"]
let searchIndex = find(fruits, "Apple”)[/code]

The searchIndex would return value if the fruit exists or nil value if it doesn’t exist.

[code language=”swift”]println("Fruit index is \(searchIndex)”)
[/code]

 

The proper way to handle this by using Optional binding method.

[code language=”swift”]if let searchIndex = searchIndex {
println("Fruit index is \(searchIndex)")
} else {
println("Not available")
}[/code]

This would ensure only when searchIndex has a value the println with searchIndex gets executed.

Optional Chaining

Optional chaining is the way by which we try to retrieve a values from a chain of optional values. Let us take the following example classes.

[code language=”swift”]class School {
var director:Person?
}

class Person {
var name: String = ""
init(name: String) {
self.name = name
}
}
[/code]

 

[code language=”swift”]
var school = School()
var person = Person(name: "Jason")
school.director = person
school.director?.name
[/code]

The director property in School class is optional, when you try to access subsequent values from director property becomes optional (? mark after director when accessing name property). You can handle these optionals as shown below.

[code language=”swift”]
if let name = school.director?.name {
println("Director name is \(name)")
} else {
println("Director yet to be assigned")
}[/code]

Filed Under: Apple, ios Tagged With: Apple, Optional bindings, Optional chaining, Swift

How to display line numbers in Xcode

April 30, 2015 By Ravi Shankar Leave a Comment

Listed below are the steps to display line number in Xcode editor window. This is quite useful when you are working in a ground and want to communicate the line number of statement to other members.

Click Xcode menu option and select Preferences from the menu list

201504301024.jpg

In the Preferences window, click Text Editing tab.

201504301026.jpg

Then mark the check box with caption as Show Line numbers. Now you should be able to see the line numbers in Xcode editor window.

201504301027.jpg

Filed Under: Develop, ios, Xcode Tagged With: Line numbers, Xcode

SplitViewController example in Swift

April 1, 2015 By Ravi Shankar 4 Comments

This is a beginners tutorial on SplitViewController using Interface builder with programming language as Swift. There are also some good articles available on SplitViewController, check them out as well – nhipster and whoisryannystrom.

Create a new Single View Application.

201503290525.jpg

Choose Language option as Swift and provide a product name.

201504011302.jpg

Navigate to Main.Storyboard and select default View Controller and delete it.

201504011304.jpg

Add a Split View Controller from the object library to the interface builder.

201504011305.jpg

Using Attributes Inspector make Split View Controller as the Initial View Controller

201504011307.jpg
Select View Controller in the Interface builder then click Editor menu and select Navigation Controller under Embed In menu option.

201504011308.jpg

Rename ViewController.swift to DetailViewController.swift and change the class name as well.

201504011317.jpg

Navigate to Interface builder and set the class name for ViewController scene to DetailViewController

201504011321.jpg

Now Control + drag and drop TablevIew Prototype cell to NavigationController (DetailViewController) and select segue as show detail. Also set the identifier for the Storyboard Segue as “ShowDetailIdentifier“

201504011323.jpg

201504011326.jpg

Navigate to RootViewController (TableViewController) Provide the Identifier as CellIdentifier for the Prototype Cells.

201504011325.jpg

Right click on the Project Navigator, select New File and Choose the template as Cocoa Touch Class

201504011331.jpg

In the next screen, select subclass as UIViewController and provide a name as SplitViewController

201504011332.jpg

After creating the file, edit SplitViewController subclass to UISplitViewController. Then add the following line to the viewDidLoad method.

  splitViewController?.preferredDisplayMode = .PrimaryOverlay

The above line is to keep the PrimaryViewController (TableViewController) on top of SecondaryViewController (DetailViewController). You can change this behaviour by setting other types, check the documentation for more details.

201504011407.jpg

Now add the PrimaryViewController (TableViewController) by right clicking and selecting New File. Select Cocoa Touch class and in the subclass field pick UITableViewController. Provide the the name for the TableViewController ListTableViewController.

201504011409.jpg

Set the class name for the RootViewController (TableViewController) to the newly created class, ListTableViewController.

201504011424.jpg

Navigate to DetailViewController in the Interface builder, add a label and make it horizontally and vertically centred.

201504011524.jpg

Then add a new IBOutlet in DetailViewController and connect the Outlet to the label in interface builder.

  @IBOutlet var numberLabel:UILabel?

Also add property of type Int and the value for this property will be set during the segue transition.

var selectedIndex:Int = 1

Make changes to the viewDidLoad method, to set the value for the label and to add back button to the navigation bar.

override func viewDidLoad() {

super.viewDidLoad()

  

numberLabel?.text = “\(selectedIndex)“

  

// add back button to the navigation bar.

  

if splitViewController?.respondsToSelector(“displayModeButtonItem”) == true {

navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem()

navigationItem.leftItemsSupplementBackButton = true

}

}

In the ListTableViewController, add the following code that sets the datasource.

  let names = [“One”,“Two”,“Three”,“Four”,“Five”,“Six”,“Seven”,“Eight”,“Nine”,“Ten”] (class level declaration)

  // MARK: – Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {

return 1

}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return names.count

}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCellWithIdentifier(“CellIdentifier”, forIndexPath: indexPath) as UITableViewCell

   cell.textLabel?.text = names[indexPath.row]

return cell

}

Then make changes to the prepareForSegue method to navigate to DetailViewController after setting the selectedIndex property

  override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

if (segue.identifier == “ShowDetailIdentifier”) {

var detail: DetailViewController

if let navigationController = segue.destinationViewController as? UINavigationController {

detail = navigationController.topViewController as DetailViewController

} else {

detail = segue.destinationViewController as DetailViewController

}

  

if let path = tableView.indexPathForSelectedRow() {

detail.selectedIndex = path.row + 1

}

}

}

201504011556.jpg

Download the source from here.

Filed Under: ios, iPad, iPhone, Programming, Xcode Tagged With: Demo, iPad, UISplitViewController, Xcode

  1. Pages:
  2. 1
  3. 2
  4. 3
  5. 4
  6. 5
  7. »
Next Page »

Primary Sidebar

TwitterLinkedin

Recent Posts

  • How to know the size of the folders in iCloud
  • Errors were encountered while preparing your device
  • We have blocked all requests from this device – Firebase Phone Authentication
  • iPhone is not available error message in Xcode
  • Clear CocoaPods cache, re-download and reinstall all pods

Copyright 2021 © rshankar.com