iOS for C# Developers - DevConnections Talk

Post on 15-May-2015

1.098 views 4 download

Tags:

description

Crash-course for C# developers on getting started with C#/iOS development.

Transcript of iOS for C# Developers - DevConnections Talk

iOS for C# Developers

Miguel de Icaza – Xamarin Inc@migueldeicaza

iOS Adoption

.NET Event Idiom

Objects raising a number of events

F.Clicked += EventHandler

Storage for properties/events:

• either in object• Or uses bags, like

DependencyProperties

MyControl

OnEnter

OnLeave

Clicked

Background

Font

MyControlDelegate

Objective-C Delegate Idiom

Objects use a peer object to post notifications

f.Delegate = new myDelegate ();

Must implement methods in MyDelegate

MyControl

OnEnter

OnLeave

Clicked

Background

Font

Delegate

Objective-C Action/Target

• Poor man’s C# delegate.

• In .NET this is mapped to a C# delegate– Use methods– Anonymous methods– Lambdas

C# on iOS

• All the features you come to expect from C#

• IDEs:– Visual Studio on Windows– Xamarin Studio on Mac

• Think of iOS as another platform to target– Just like you ASP.NET or WPF are– Same level of code sharing

APIs for C# Developers on iOS

• .NET’s Base Class Libraries– mscorlib, System, System.Core, System.Data– System.Web.Services– etc

• Native iOS APIs surfaced as C# classes– Mapped with some artistic liberties:– Follow .NET’s Framework Design Guidelines

iOS APIs Surfaced to .NET

• Objective-C to C# bridge– Special runtime support for these– Integrates the Object Systems

• Object Oriented C Code– Manually mapped to C# classes

• Mostly CoreFoundation derived types

• Regular C code– Mapped to C# classes as well

iOS APIs for .NET

• iOS APIs are weakly typed– Similar to .NET 1.0 code

• C# bindings are strongly typed– Helps explore the API– Let the IDE help you write your code

• Async-ified (same rules as .NET async)

THE BASICS

Starting Up

• C# Main () method– Call UIApplication.Main – Pass the name of your application delegate class

• System creates UIApplication class– Instantiates your UIApplicationDelegate

• UIApplicationDelegate methods invoked– FinishedLaunching performs UI setup

Complete app

UIApplicationDelegate

• How the operating system talks to your app

• Mostly deals with state:– Starting up (fresh, openUrl request)– Suspending– Resuming– Respond to notifications– Background downloads

• Also: data security, UI orientation

Hierarchy

Screens

Windows

ViewControllers

Views or ViewControllers

UIScreen

• Represents a screen available in your device

• UIScreen.MainScreen is the main screen– Same as UIScreen.Screens [0]

• Other screens used for external connectors

UIWindows

• Developers use one (system does others)– Routes events– Sets the Root View Controller

• UIWindow.RootViewController– Must be set by the end of running your FinishedLaunching method.

UIView

• Base class for all UI Elements

BackgroundColor = UIColor.Red

UIView Subclasses

UIView

UIControl

UIButton

UIPicker

UISlider

UISwitch

UIStepper

UITextField

UIImageView

UILabel

UIProgressView

UIScrollView

UITableView

UITextView

UICollectionView10,000 foot view, not comprehensive

Simple UIViews

Controls

ScrollViews

UIViews are General Containers

Can be arbitrarily nested

UIView methods:AddSubview (UISubview)RemoveFromSuperview ()

Unlike Gtk/Winforms: Everything is a container

Can be Arbitrarily Nested

UIView’s

• Frame– Superview coordinates– RectangleF

• Bounds– Size in UIView’s

coordinates

• Transform– 2D Affine transformation

• Center– Superview coordinates

X, Y = (20,10)

W,H=(50,30)

Center X, Y = (35,20)

2D Affine Transforms

Rotation Translation Shearing Scaling

UIView’s

• Frame– Superview coordinates– RectangleF

• Bounds– Size in UIView’s

coordinates

• Transform– 2D Affine transformation

• Center– Superview coordinates

45’ rotation over the center

UIView Center+Affine Transforms

• Frame– Superview coordinates– RectangleF

• Bounds– Size in UIView’s

coordinates

• Transform– 2D Affine transformation

• Center– Superview coordinates

Custom UIView - Rendering

• Override Draw (RectangleF region) method– Must paint the entire requested region

• Obtain the UIGraphics’ current draw context

• CGContext: Immediate graphics API– Similar to System.Drawing on Windows.Forms– Not retained, like Silverlight

Samplepublic override void Draw (RectangleF rect){ using (CGContext context = UIGraphics.GetCurrentContext ()) { // turn on anti-aliasing context.SetAllowsAntialiasing (true); // loop through each spot and draw it foreach (Spot s in touchSpots) { context.SetFillColor (s.Red, s.Green, s.Blue, s.Alpha); context.FillEllipseInRect (new RectangleF (s.Point,size)); } }}

Custom UIViews – Touch Handling• Configure properties:

– UserInteractionEnabled, MultipleTouchEnabled

• Override:TouchesBegan:

– User touched the UI

TouchesMoved– Updated locations

TouchesEnded– User lifted fingers

TouchesCancelled– System cancelled (for example, incoming call)

Animation

• UIKit is powered by an animation framework– Details, beyond the scope of today’s talk

• Certain properties can be animated:– Frame, Bounds, Center, Transform– Alpha, BackgroundColor, ContentStretch

• Very little setup needed

Animation + Async

• UIView.Animate methods

• Use AnimateNotifyAsync family of methods– Duration– Lambda to update visual properties– Options controlling animation

• Await on the call– Will resume execution after animation completes

Sample

Dynamics – new in iOS 7

• Introduces a physics engine into the UI – Gravity– Collision– Attachment– Snap– Forces/Pushing

Gravity + Collision Detection

UIViewController

• Typically a full screen of content

• Host for your views– In charge of layout – Orientation changes– Provides event routing for your views

• Some can host other UIViewControllers– “UIViewController Containment”

• UIViewController.View property is the root UIView

Manually Creating your UI

Using a UI Designer

UIViewControllers in UIKit

UIViewControllers in UIKit.

UIViewController

UIActivityViewController

UICollectionViewController

UINavigationViewController

UIPageViewController

UIReferenceLibraryViewController

UITabBarViewController

UITableViewController

UISplitVuewController

Built-in UI

Building Blocks

Built-in UI

UIActivityViewController UIReferenceLibraryViewController

Other UIViewControllers• AddressBookUI

– ABNewPersonViewController– ABPersonViewController– ABUnknownPersonViewController

• EventKitUI– EKCalendarChooser– EKEventViewController

• GLKit– GLKViewController

• GameKit– GKMatchmakerViewController

• MediaPlayer– MPMediaPickerController– MPMoviePlayerViewController.

• MultipeerConnectivity– MCBrowserViewController– MCPeerPickerViewController

• PassKit– PKAddPassesViewController

• QuickLook– QLPreviewController

• Social/Twitter– SLComposeViewController– TWTweetComposeViewController

• StoreKit– SKStoreProductViewController

Some Examples

ABNewPersonViewController EKEventViewController

Some Examples

TWTweetComposeViewController MPMoviewPlayerViewController

UIViewControllers and Storyboards

• Name your class in the designer– Will be reflected in your code

• Only after ViewDidLoad () are objects created– Any references to other views or controllers– Wont be valid until after this method is called

Presenting View Controllers

• Given a current UIViewController, call:– PresentViewController– PresentViewControllerAsync

• Modality of controller:– bool ModalViewController {get;set}

• You can build your own visual transition– And control every step of it

UIControl

Common Controls

Strongly Typed Notifications

• NSNotificationCenter– Application Message Bus– Hub for posting messages• “Keyboard will appear”• “Font size changed”

• Strongly typed in C#– Class.Notification.ObserveXXXX ()

Strongly Typed

THREE VIEWS TO MASTER

UIScrollView

• Where the magic originates• Powerful control that handles scrolling– Pagination, scrolling, smooth motion

• Must see: Series of WWDC talks on it– Every possible trick and hack

UITableView

• Most UI in iOS is a table• Variable height• External Data Source– Request Section/Row– Return UITableViewCell

• External Delegate

• Powerful• And Cumbersome

MonoTouch.Dialog – UITableView made easy

• Switches the model– From callback to fetch data (very scalable)– To dump all data into view (easy, not scalable)

• Elements:– Provide cell-specific style renderers

MonoTouch.Dialog sample

• Sample program• Mimics Sounds Settings

UICollectionView

• Arbitrary collections• In any form you want– Table, Grid– Baseball diamond– Circle– Or anything you can

provide rules for

More Resources

Wallace McClure’s talkMechanics of it - Right after this oneIslander IE

• http://developer.apple.com/ios• Apple’s site

• http://docs.xamarin.com/ios– Docs, tutorials on C# and iOS

• http://planet.xamarin.com– Technical Blogs from the community