Download presentation
Presentation is loading. Please wait.
Published byAdrian Whitehead Modified over 8 years ago
1
Introduction to Xamarin.iOS
2
1.Introduce the development tools 2.(De)constructingthe application 3.Adding views and behavior Objectives
3
Introduce the development tools
4
1.What is Xamarin.iOS? 2.Explore the IDE choices 3.Creating an app using the project templates TasksTasks Xamarin.iO S
5
You must have the following to build iOS apps: Reminder: Development Setup Mac running OS X with the latest version of Xcode Xamarin tools on all your development machines (both Mac and Windows) Setup help is provided in the XAM101 orientation class, if you have not setup your environment yet we highly recommend you attend that class first
6
What is included in Xamarin.iOS? Xamarin.iOS includes both compile-time and runtime components C#C# C# compiler for Mac Native compiler and linker Runtime services (GC, type checking, etc.) Core.NET Libraries
7
Xamarin allows you to build iOS applications using C# /.NET with either Choose your IDE Note: even though Xamarin Studio is installed and runs on Windows, it does not support iOS application development Microsoft Visual Studio on Windows Xamarin Studio on Mac OS X
8
Creating a new iOS application Both IDEs have project templates to create a new iOS application Xamarin Studio Visual Studio
9
Project templates provide starting point for different application styles Choosing a project template Single View App The Single View app template creates an app with single screen to display data, this is the simplest template to start with
10
Project templates provide starting point for different application styles Choosing a project template Single View App Master- Detail App Master/Detail provides a list of items with a built-in detail screen
11
Project templates provide starting point for different application styles Choosing a project template Single View App Master- Detail App Page- Based App Page-Based App creates a multi-page application where you swipe between the pages – similar to a book reader
12
Project templates provide starting point for different application styles Choosing a project template Single View App Master- Detail App Page- Based App WebVie w App WebView Apps allows you to create apps that use the ASP.NET Razor templating engine to render the screens
13
Project templates provide starting point for different application styles Choosing a project template Page- Based App WebVie w App Tabbe d App Single View App The Tabbed app template creates apps that use a tab bar to display multiple pages in the application
14
*Visual Studio includes "Universal" templates which support iPhone + iPad in a single app using two separate views *This is an older set of templates which have been deprecated by new support in iOS8 for adaptive design Universal application templates
15
*Use the Build menu or toolbar to compile/run the application Building your application Both IDEs have shortcut keys to build
16
*Xcode includes a simulator that can run your app on the Mac, this is the easiest way to test your applications initially Testing your application IDEs provide access to the simulator selection directly on the toolbar
17
What about deploying to a device? *To test on a device, you will need to register each device and get a set of signing certificates from Apple *Must have a registered developer Apple account to deploy to a device (can be paid or free) *Watch the lightning lecture on provisioning an iOS device for testing
18
Creating and running your first iOS application Group Exercise
19
1.What is Xamarin.iOS? 2.Explore the IDE choices 3.Creating an app using the project templates Summary Xamarin.iO S
20
(De)constructing the application
21
1.Exploring the created project 2.Model-View-Controller 3.Delegates and Protocols TasksTasks
22
Let's explore the created project *The created project is contained in a standard.NET solution and has several related files that work together to create the application Source Files (C#) UI definitions (Storyboard + XIB) Metadata (property lists)
23
Explore the created project Demonstration
24
Let's explore the created project *IDE loads a solution file (.sln) which contains one or more project files (.csproj), each project generates some sort of output – typically an executable or library *Uses MSBuild-basedprojects which can be loaded into either Visual Studio or Xamarin Studio – can switch back and forth between Mac and Windows if desired
25
Let's explore the created project *References folder contains required compile and runtime assemblies *Can add new assemblies through context menu by right-clickingon the references folder *Referenced assemblies must either be compatible portable class libraries (PCLs), or compiled against Xamarin.iOS – cannot use desktop.NET assemblies directly
26
Let's explore the created project *Components folder contains components downloaded from the Xamarin Component Store (components.xamarin.com) *Packages folder contains any referenced Nuget packages (www.nuget.org) *Components/Packagesmust either be compiled as a portable library, or against Xamarin.iOS
27
Let's explore the created project *Resources folder contains additional assets needed at runtime such as images *Files in this folder should have a build action of BundleResource and are included with the generated application package to be installed on a device *Template creates some icon assets and a launch screen displayed while the app starts
28
Let's explore the created project * AppDelegate.cs is responsible for creating the main window and listening to operating system events *Contains a class implements that derives from iOS UIApplicationDelegate *Must override virtual methods in class to process received operating system events
29
Let's explore the created project *iOS uses property list files to store application metadata as key/value pairs § Entitlements.plist lists external Apple services your app wants to interact with such as in-app purchases, HealthKit or push notifications § Info.plist identifies app icons, version number, app name and other app details *Both IDEs include a GUI editor for these files to edit the most common settings
30
Let's explore the created project * Main.cs contains the main entry point for the application in the form of a standard.NET static void Main() *It starts up the iOS UI framework (UIKit) and identifies the App Delegate, which will in turn bring up the initial screen for the application *Be cautious about adding code into the Main method – iOS has time limits on app launches!
31
Let's explore the created project * MainStoryboard.storyboard contains the declarative (XML) definition of all the screens in the application (this file is not present for game-based templates) *Xamarin.iOS includes a built-in designer integrated into both IDEs, or you can use Interface Builder in Xcode *Primary storyboard is identified in the info.plist
32
Let's explore the created project * (Root)ViewController.cs contains the behavior for the initial screen, each screen in your app will have a view controller source file associated with it * (Root)ViewController.designer.cs is a partial-classdefinition used by the designer to connect elements in the storyboard with the code defined in the view controller *This follows the MVC design pattern
33
*iOS uses several terms which might be unfamiliar or have different meanings than what you are used to iOS Terminology ModelViewView Controlle r DelegateDelegate ProtocolProtocol
34
*Model-View-Controller(MVC) is an established architectural design pattern to logically separate the UI, data and behavior of an app *This is the cornerstone design pattern for all iOS applications and it's usage is enforced by the iOS API design What is MVC? Model View Controlle r
35
*The Model contains data, information and logic that is considered part of the business layer of your application; this is almost all developer- created ModelModel Calculatio n Function s Data Entities Validatio n Logic Persistenc e Logic Processin g Logic …
36
*The View contains all the visual components the user sees and interacts with such as buttons, sliders and text, all of which derive from a standard class UIView *Views are composed and can be defined in code or declaratively using a Storyboard or XIB file ViewView
37
*The Controller is the moderator between the model and the view, in iOS these are classes that derive from UIViewController Controller ViewView ModelModel User Actio n Update data notifynotify Updat e UI Controlle r
38
*The Controller is the moderator between the model and the view, in iOS these are classes that derive from UIViewController Controller ViewView User Actio n Updat e UI iOS provides several implementations of UIViewController to manage different UI styles and behaviors such as navigation, alerts and tables ModelModel Controller Model
39
*App must identify a single view controller to be the starting controller Defining a Root Controller
40
*App must identify a single view controller to be the starting controller Defining a Root Controller
41
*App must identify a single view controller to be the starting controller Defining a Root Controller
42
*App must identify a single view controller to be the starting controller Defining a Root Controller
43
Putting it all together Main() UIApplication.Main() call s parsesparses Info.plis t Run Loop startsstarts FinishedLaunching() call s AppDelegate UIApplication createscreates UIWindowRootViewController creates / assigns iOSiOS customcustom
44
Create a single screen application and add controls
45
1.Describe the iOS Designer 2.Identify controls and properties 3.Demonstrate the designer workflow 4.Work with subviews Tasks
46
A UIView defines a rectangular area on the screen and provides: Reminder: UIView Visualizatio n Layout for subviews Event publishing
47
A UIViewController provides view management for a single screen Owns a UIView (root view) and receives lifetime notifications from it Acts as the mediator between the view(s) and the data/logic/model(s) Reminder: View Controllers
48
The Xamarin.iOS designer is a visual drag + drop editor for creating and editing screens (View Controllers + Views) in your iOS applications The iOS Designer Xamarin Studio Visual Studio
49
The iOS Designer has several windows which you use to examine, visualize, design the UI of your application Parts of the Designer Designe r Surfac e Propertie s Explorer Documen t Outline Toolbo x Designe r Toolbar
50
Tour the Xamarin.iOS designer Demonstratio n
51
iOS supports two designer file formats Storyboards vs. XIBs Storyboards let you design multiple screens together with the relationships between them; this is the default file created for your app XIB is the original format which defines a single screen or part of a screen; this is used today for the Launch Screen
52
Most of the time you will only have one Storyboard in your app, but you can add as many as you need to segregate or share your UI definitions Info.plist identifies the one to start the app with and is editable under iOS Application settings Using Storyboards Xamarin Studio Visual Studio
53
Drag widgets onto the designer surface and then set properties Workflow [Xamarin Studio] Can drag UIView from the toolbox … then change the background color
54
Drag widgets onto the designer surface and then set properties Workflow [Visual Studio] Can drag UIView from the toolbox … then change the background color
55
Layout and subviews Controls (subviews) can be positioned onto the root UIView (superview) superview subview s Use the document outline view to see relationships
56
Can take advantage of the view architecture to create composite controls by nesting controls within a UIView Composite controls can be made reusable and are easily moved or animated as a group by adjusting the parent view Composite controls
57
Describe and use Auto Layout
58
1.Describe the Auto Layout system 2.Identify constraints 3.Add constraints using the Designer Tasks
59
There are several things which can affect the layout of your UI at runtime Orientation changes Running on a device with a different resolution or form factor Positioning dynamic content Working with user-selectable fonts Localization Responsive interface design
60
Apple has two APIs to manage layout rules in the UI design Layout solutions Autoresizing Masks You define each side of the frame with either a "flexible" or "fixed" margin to decide if it stretches with, or is pinned to the parent
61
What is Auto Layout? Can set heights and widths Auto Layout is a system that helps organize the application UI by describing relationships between visual elements Can set positions relative to other views (or the parent view)
62
Auto Layout in the Designer Storyboard designer allows us to visually manage Auto Layout constraints without writing any code Enabled by default but can be turned on and off in the Storyboard properties in Xamarin Studio or Visual Studio – this will cause the Storyboard to revert back to the "Springs and Struts" approach
63
Constraints determine one aspect of a UIView position or size and essentially form the rules that describe the layout What are Constraints? view.left = superview.left view.height = 0.5 * superview.height view.top = superview.top + 20 view.top = otherView.bottom + 8 view.height = 0.5 * view.width
64
Constraints are: Applied to views Cumulative Prioritized Able to cross views They decide the position and size of the UIView they are applied to Constraint behavior
65
The designer adds the constraints directly into the Storyboard and iOS will then apply them when the UI is inflated at runtime Xamarin.iOS Designer constraints are shown graphically and can be changed either on the designer surface or in the property pad
66
In the iOS Designer, single-tap views to toggle between editing the frame and editing constraints Constraint “Mode” Circles used to adjust the frame Bars used to create constraints Single tap to toggle
67
Use the dragging control decorators on a view to create a constraint with itself, the parent, or a sibling view Adding Constraints Can select and drag the handles and drop onto the target view
68
Designer supports manipulation of three types of constraints Types of Constraints Spacing Constraint s Sizing Constraint s Alignment Constraint s
69
Spacing constraints allow you to position a view relative to another view (or parent) by dragging the T-handle shapes on each edge Spacing constraints
70
Sizing constraints allow you to control a views width and height (can be a constant, fixed to another constraint, or an inequality) by dragging the center "I" bar shape on the right and bottom edge of the view Sizing constraints
71
Alignment constraints allow you to align a view to the X or Y axis of it's superview or a sibling Alignment constraints
72
Interact with controls and views programmatically
73
1.Associate a class for the UIViewController 2.Adding actions to a control 3.Naming views 4.Inspect outlets and actions Tasks
74
Applying behavior to the views of an app is essential if you want your code to respond to user interactions Keep in mind that not every view needs to be accessible in code – only things that drive the business logic or display results User interaction
75
In order to apply behaviors to your controls the UIViewController must have a class associated to it Assign a class Select the grey bar on the view controller Xamarin will populate a C# file in the solution Assign it a class name
76
There are two recommended practices to follow when naming your backing class: 1)Name should reflect what the screen does or manages this makes it easier to identify when you have multiple screens 2)Name should end with the " ViewController " suffix to make it obvious what it is Naming guidelines
77
When you assign a class in the designer, the class will be marked as a partial class and split into two files Partial classes [main file] The.cs file is where you will code the behaviors for your view controller
78
When you assign a class in the designer, the class will be marked as a partial class and split into two files Partial classes [designer file] The designer.cs file is a representation of the storyboard for the compiler, you should never change this file directly since it is auto-generated
79
Classes that will be instantiated by iOS need to be registered with the Objective-C runtime – this is done through a [Register] attribute Registering a class with iOS
80
iOS uses a custom constructor to create the View Controller View Controller constructor public partial class ViewController : UIViewController { public ViewController(IntPtr handle) : base(handle) { }...... } Must have this constructor and chain to the base if iOS is going to instantiate this View Controller (e.g. load from a Storyboard)
81
Can name your views to make them accessible to View Controller code Name your view Select the control in the design surface and then set the Name Hint: as with naming View Controllers, it is advisable to use a name which shows the purpose and then the type – to make it easier to identify in code
82
An outlet is a property that is tied to a control in the UI design Control must be defined in the screen owned by the View Controller Property is private to the View Controller class Decorated with an [Outlet] attribute to register it with iOS What is an Outlet? Designer adds this code to your designer.cs file when you name a control in the storyboard [Register ("TodoListViewController")] partial class TodoListViewController { [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIButton LoginButton { get; set; }... }
83
Actions are methods that are called by a view in response to a runtime interaction or event In the Designer you can choose Events on the properties pane and associate methods to the actions the selected view raises at runtime Can double-click on most controls to add a handler for the "default" action What is an Action?
84
Actions wired up in the designer are mapped to partial methods defined in the designer portion of your View Controller class and implemented in your main source file Implementing Actions [Action ("DoLogin:")] ViewController.designer.cs [GeneratedCode ("iOS Designer", "1.0")] partial void DoLogin (UIButton sender); partial void DoLogin(UIButton sender) { // TODO: add logic here } ViewController.cs
85
Apply navigation using segues
86
1.Add a second UIViewController 2.Code a button to present a view controller 3.Code a button to dismiss a view controller 4.Utilize segues to create navigation Tasks
87
#1 Most applications consist of more than one screen Can define multiple screens in the Storyboard Can then display secondary screens through code, or by defining the relationships in the designer Multi-screen apps #2 #3
88
You can add screens to your app by dragging a view controller onto the storyboard and then add your UIViews onto it Adding screens to the storyboard
89
All new view controllers added to the storyboard should be assigned a backing class Create a class
90
Instantiating a View Controller View Controllers defined in Storyboards must be created through the Storyboard APIs to get the proper views created partial void ShowAboutPage(UIButton sender) { UIStoryboard storyboard = this.Storyboard; AboutViewController viewController = (AboutViewController) storyboard.InstantiateViewController("AboutViewController");... }
91
Must set the Storyboard Id on the View Controller to identify it to the Storyboard from code – a good practice is to give it the same name as the class that defines it in code Naming a View Controller AboutViewControlle r
92
Can use the PresentViewController method to display a new View Controller in a modal fashion on top of your existing screen Present the view controller this.PresentViewController(viewController, true, null); partial void ShowAboutPage(UIButton sender) { UIStoryboard storyboard = this.Storyboard; AboutViewController viewController = (AboutViewController) storyboard.InstantiateViewController("AboutViewController"); }
93
To return to the previous View Controller, use the DismissViewController method in your active view controller Dismiss a modal view controller this.DismissViewController(true, null); partial class AboutViewController : UIViewController {... partial void OnGoBack(UIButton sender) { }
94
Can customize the animation used to transition to the new controller through the ModalTransitionStyle property Changing the transition style partial void ShowAboutPage(UIButton sender) { AboutViewController viewController =...; viewController.ModalTransitionStyle = UIModalTransitionStyle.PartialCurl; this.PresentViewController(viewController, true, null); }
95
Add a second screen to your app and code a button to navigate to it Individual Exercise
96
Segues (“segways”) define the transitions between the screens of our app in the designer What is a Segue?
97
The sourceless segue indicates the root (initial) view controller Sourceless segue Click+Drag to move the sourceless segue to a different screen … or select the view controller and check the initial view controller checkbox
98
Use Ctrl+Drag to create segues between two screens Create a segue relationship The blue connector appears as you drag your mouse from a control to the target screen
99
Segues have properties such as an ID and transition type Segue properties Select the segue on the storyboard to view segue options
100
There are two types of relationships that can be created: Relationship types Actio n Manua l Action segues are defined between an active view such as a button and a screen – these can be trigger the segue directly Manual segues are defined between a non-active view or view controller and a screen – these must be activated in code
101
Run a segue from code Can use PerformSegue in a View Controller to initiate a segue from code – this allows you to define the transition in the Storyboard, but decide when to run it based on your application logic partial void ShowAboutPage(UIButton sender) { this.PerformSegue("AboutSegue", this); } Takes the identifier of the segue.. And the sender
102
Sometimes you need to stop a segue from occurring due to some application state Stopping a segue public override bool ShouldPerformSegue( string segueIdentifier, NSObject sender) { if (IsScreenDataValid() && segueIdentifier != "AboutSegue") return false; // do not run any segue except About return true; // allow segue }
103
Sometimes you need to just setup the target screen with some data from the source – can use PrepareForSegue override Influence a segue public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) { if (segue.Identifier == "AboutSegue") { var vc = segue.DestinationViewController as AboutViewController; vc.RegisteredUserName =...; // Some custom property }
104
Thank You! Please complete the class survey in your profile: university.xamarin.com/profile
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.