37
Text Swift Programming for iOS A Modern Alternative to Objective-C

Swift

Embed Size (px)

Citation preview

Text

Swift Programming for iOSA Modern Alternative to Objective-C

What is Swift?

Swift is a new programming language created by Apple as the language of their future. Swift was originally announced during the Apple Worldwide Developer Conference in June of 2014. Apple had used Objective-C, originally created for the Mac, for over 20 years. Swift was created to make writing code easier and more concise. Swift is perfect for beginners and has lowered the barriers so that anyone can make apps.

Swift Languagefast, modern, safe, interactive programming language

cleaner, easier to read than the bizarre syntax of Objective-C.

no semicolons required (with one statement per line)

Initial Requirements

A Macintosh computer

Register as an Apple Developer

Need an Apple ID and register at http://developer.apple.com/programs/register

Install Xcode

iOS Simulator

No camera or video access

$99/year to enroll in iOS Developer program to test on real iOS devices/submit to App store

Prototypinghttps://popapp.in/

https://proto.io/

https://www.flinto.com/

http://www.invisionapp.com/

Basically capture sketches with camera and define tap areas and transitions to target pages

Users try out prototypes using a shared web link

Prototyping with Keynote

Keynotpia — mock templates

http://keynotopia.com/keynote-mockups-templates/

Xcode PlaygroundLike a console — try out code and view live execution of that code

Optionalsfunc findStockCode(company: String) -> String? { if (company == "Apple") { return "AAPL" } else if (company == "Google") { return "GOOG" }

return nil }

var stockCode:String? = findStockCode("Facebook") let text = "Stock Code - " let message = text + stockCode // compile-time error println(message)

Unwrapping Optionals

var stockCode:String? = findStockCode("Facebook") let text = "Stock Code - " if stockCode{ let message = text + stockCode! // force unwrap println(message)

}

Optional Chainingclass Stock { var code: String? var price: Double?

func findStockCode(company: String) -> Stock? { if (company == “Apple”) {

let aapl: Stock = Stock() aapl.code = “AAPL” aapl.price = 90.32

return aapl } else if (company == “Google”) { let goog: Stock = Stock() goog.code = “GOOG” goog.price = 556.36

return goog } return nil

}

Optional Chaining

if let stock = findStockCode(“Facebook”) { if let sharePrice = stock.price{

let totalCost = sharePrice * 100 println(totalCost)

} }

Auto Layoutbuild apps to support all screen resolutions across iPhone and iPad models of hardware

Retina display: 1 point = 2 pixels

iOS handles translation between points and pixels

Auto Layout ConstraintsExample: button centered horizontally and vertically regardless of screen resolution and orientation (landscape/portrait)

Two constraints defined:center horizontallycenter vertically

In Xcode you use the Auto layout menu or Control-drag

Shift-Option click storyboard to see previews without running the simulator(s)

Auto Layout OptionsAlign — create alignment constraints, such as aligning the left edges of two views

Pin — create spacing constraints, such as defining the width of a UI control

Issues — resolve layout issues; Xcode senses when placement or layout dynamics violate a constraint

Resizing — specify how resizing affects constraints

Protocolsfoundation classes in iOS such as UITableView are organized into frameworks (such as UIKit)

UITableViewDelegate and UITableViewDataSource are protocols in Swift. This is similar to an interface or contract in normal OOP constructs.

Implementing Protocols

Interface/Protocol requires the data source and number of rows to display

tableView(_:numberOfRowsInSection:)

tableView(_:cellForRowAtIndexPath:)

dequeueReusableCellWithIdentifier method retrieves a reusable table cell from the queue with the cell identifier defined in the Storyboard. That way, memory is not allocated for each row of data, but is reused.

Hide Status Bar

In your view controller code add this method:

Constraining a Table ViewGo to the storyboard and select the table view. In the Auto Layout menu, click the Pin button to open the Pin Tool menu. Select each of the dashed red line symbols. Once selected, the dashed red line turns to a solid red line. Click the “Add 4 Constraints” button to define 4 spacing constraints for each side of the UITableView. In particular, we want to ensure that the bottom of the UITableView doesn’t go beyond the Bottom Layout Guide. If you expand the constraints items in Document Outline, you’ll find two horizontal space constraints and two vertical constraints. The two horizontal space constraints ensures that the left & right side of table view will stretch to the edge of the view controllers. The vertical constraints are used to resolve the 3.5-inch screen issues.

DelegationThe delegate pattern is very common in iOS programming. Each delegate is responsible for a specific role or task to keep the system simple and clean. Whenever an object needs to perform a certain task, it depends on another object to handle it. This is known as “separation of concerns” in software design. The UITableView class applies this design concept. The two protocols are designed for different purposes. The UITableViewDataSource defines methods that are used for managing table data. It relies on the delegate to provide the table data. On the other hand, the UITableViewDelegate protocol deals with the section headings and footers of the UITableView, plus, handles the table row selection and cell reordering.

Which methods to implement in UITableViewDelegate?

Online iOS Developer Reference

https://developer.apple.com/library/ios/navigation/

Access documentation right from Xcode with control-command-? while cursor on a class or protocol

Handling Table Row Selection

tableView(_:didSelectRowAtIndexPath:)

MVC and SoC“At the heart of MVC, and the idea that was the most influential to later frameworks, is what I call Separated Presentation. The idea behind Separated Presentation is to make a clear division between domain objects that model our perception of the real world, and presentation objects that are the GUI elements we see on the screen. Domain objects should be completely self contained and work without reference to the presentation, they should also be able to support multiple presentations, possibly simultaneously. This approach was also an important part of the Unix culture, and continues today allowing many applications to be manipulated through both a graphical and command-line interface.” —Martin Fowler http://www.martinfowler.com/eaaDev/uiArchs.html#ModelViewController

Model – responsible for holding the data or any operations on the data. The model can be as simple as an array object that stores all the table data. Add, update and delete are examples of the operations. These operations are usually known as business rules.

View – manages the visual display of information. For example, UITableView shows information in a list format. Or the UIButton that appears on screen is another example.

Controller – the bridge between model and view. It translates the user interaction from the view (e.g. tap) into appropriate action to be performed in the model. For example, the user taps a delete button in the view. Consequently, the controller triggers a delete operation in the model. Once finished, the controller requests the view to refresh itself so as to reflect the update of the data model.

Scene and SegueNavigation Controller — a UI component like Table View which provides a drill-down hierarchical interface

Embed a view controller within the Navigation Controller and create the segue (transition) between scenes in Interface Builder in the Storyboard

scene within Storyboard is a single view controller and its view

each scene has a dock with action and outlet connections between the view controller and the view

Segue sits between scenes and manages the transition between scenes — like “push” and “modal”

Navigation Bar AppearanceUINavigationBar.appearance().barTintColor = UIColor(red: 231.0/255.0, green: 95.0/255.0, blue: 53.0/255.0, alpha: 0.3)UINavigationBar.appearance().tintColor = UIColor.whiteColor()if let barFont = uiFont(name: “AvenirNextCondensed-DemiBold”, size: 22.0){ UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor(), NSFontAttributeName:barFont] }

http://iosfonts.com

Hiding Navigation BarRestaurantTableViewController.swift:override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.hidesBarsOnSwipe = true }DetailViewController.swift: override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.hidesBarsOnSwipe = false

self.navigationController?.setNavigationBarHidden(false, animated: true)

}

Setting Status Bar StyleGlobal app change: Disable “View controller-based status bar appearance” and set status bar style in AppDelegate method didFinishLaunchingWithOptionsUIApplication.sharedApplication().statusBarStyle = .LightContent

View controller specific by overriding preferredStatusBarStyle method:override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent}

For global change, set boolean value to “NO”

Enabling Self Sizing Cells

tableView.estimatedRowHeight = 36.0 // set height to existing prototype cell tableView.rowHeight = UITableViewAutomaticDimension //set to default iOS row height

Requires AutoLayout to be configured

Add code to controller’s (Detail View Controller in this case) viewDidLoad method

References

Ng, S. Beginning IOS 8 Programming With Swift. 1st ed. AppCoda Limited, 2014. Print.

Nepster, J. The Swift Programming Language. 1st ed. Jay Nepster, 2015. Print.

Derico, S. (2015) Introducing iOS 8. 1st ed. Sebastopol, CA: O’Reilly Media, Inc.

Nahavandipoor, V. (2015) iOS 8 Swift Programming Cookbook. 1st ed. Sebastopol, CA: O’Reilly Media, Inc.

Deitel, P., et al. (2015) iOS 8 for Programmers. 3rd ed. Upper Saddle River, NJ: Prentice Hall.