Xamarin Tutorial

March 20, 2018 | Author: Alex Hitch | Category: Xamarin, Xcode, Integrated Development Environment, Microsoft Visual Studio, System Software


Comments



Description

Hello, Mac OverviewUsing Xamarin.Mac, you can create native Mac applications by using the same UI controls that you would if you were writing the application in Objective-C and Xcode, except you have the flexibility and elegance of a modern language (C#), the power of the .NET Base Class Library (BCL), and a first-class IDE (Xamarin Studio) at your fingertips. Additionally, Xamarin.Mac integrates directly with Xcode so that you can use the integrated Interface Builder (IB) to create your application’s user interface. In this tutorial, we’re going to walk through creating a simple application from start to finish. We’ll cover the following items: Xamarin Studio (MD) – Introduction to the Xamarin IDE (Xamarin Studio) and how to create Xamarin.Mac applications with it. Anatomy of a Xamarin.Mac Application – What a Xamarin.Mac application consists of. Xcode’s Interface Builder – How to use Xcode’s Interface Builder to define your application’s user interface (UI). Outlets and Actions – How to use Outlets and Actions to wire up controls in the UI. Deployment/Testing – How to run your application and test it out. G G G G G The following is a screenshot of the application that we’re going to build, running in Mountain Lion (Mac OS X 10.8): or via a Spotlight search for “Xamarin Studio. Introduction to Xamarin Studio Nearly all Xamarin. Let’s begin by launching Xamarin Studio. Xamarin Studio is a free. You can find it in either your Applications directory.Mac tutorials are based on using Xamarin Studio as the Integrated Development Environment (IDE) of choice. and is very similar to other IDEs such as Eclipse or Visual Studio.Let’s jump in. open-source IDE.” Xamarin Studio should open up and look something like the following: . .Mac Project From the Xamarin Studio Home screen. Creating a New Xamarin.Mac application. This will create a new single window Mac application.Mac Project template.Let’s jump right in and begin our first Xamarin. choose Start a New Solution: In the left-hand pane. choose C# > Xamarin. and then.Mac. in the center pane. select Xamarin. The Project If you’re familiar with iOS programming. Let’s take a look at the files in the project: G G – This contains the main entry point of the application.NET application. a lot of concepts will cross over here. Xamarin Studio will create a new Xamarin.If you are using the trial. etc. In fact.cs – This file contains the main application class that is responsible for listening to events from the operating system. In this case. and a code editor pad that allows you to view and edit the selected file. Main. which is a slimmed-town version of Cocoa. and click OK. supporting libraries.Mac application and solution that looks something like the following: This should be pretty familiar territory if you’ve used an IDE before. this contains the very first class and method that is run.cs . select "Mac (open source)" which uses the more limited set of APIs. AppDelegate. just as you would if you were building a standard . Let’s name it Hello_Mac. A solution is a container that can hold one or more projects. iOS uses the CocoaTouch framework. you’ll notice a lot of similarities here. Xamarin Studio uses Solutions and Projects. used by Mac. Xamarin Studio has created both a solution and an application project for you. When the application is launched. There is a Solution Explorer “pad” that shows all the files in the solution. If you wanted to. you could create code library projects that the application project uses. projects can include applications. test applications. Choose a location where you’d like the solution to reside. the exact same way that Visual Studio does. In fact. Main (args). a controller can be thought of the main engine of any particular view.cs The AppDelegate. using MonoMac. mainWindowController. The first line instantiates a new instance of our main window controller: . which in our case is the AppDelegate class: using System. using MonoMac. NSApplication. using System. etc. adding new views (controls) to it.plist Let’s take a quick look through some of these files.xib – This is the UI for the application menu. and it’s responsible for actually creating the application window and beginning the process of displaying the view in it. We’ll cover controllers in the next guide. but for now. using System.ObjCRuntime.cs – This is the controller for the main window.cs – This file contains plumbing code that helps you integrate with the main screen’s user interface. namespace Hello_Mac { public partial class AppDelegate : NSApplicationDelegate { MainWindowController mainWindowController. CocoaTouch) uses what’s known as the Model View Controller (MVC) pattern.AppKit.MakeKeyAndOrderFront (this). using MonoMac. Let’s examine the important lines.Foundation. for every window you create (and for many other things within windows). etc. It contains a static Main method which creates a new Xamarin. We’ll explore them in more detail later. there is a controller. Next. First.ObjCRuntime.cs – This is the class that represents the main window and controls the lifecycle of it. MainWindow. are XML files that contain the definition of views (UI elements).Xib files (also referred to as Nibs for legacy reasons).xib – The UI for the main window. .cs file contains our AppDelegate class. which is responsible for the window’s life cycle. MainWindow. but it’s a good idea to understand their basics now.cs file is very simple.cs The Main. such as showing it. MainMenu. We’ll examine this in more depth in the next tutorial. The MainWindowController declaration represents what controls the actual application window. Info. Cocoa (and by derivation. icons. This method runs after the application has been instantiated. MainWindow.Foundation. using MonoMac. namespace Hello_Mac { class MainClass { static void Main (string[] args) { NSApplication.G G G G G G – This file contains application properties such as the application name. using MonoMac. } } } This code is probably unfamiliar unless you’ve built an iOS application before.Init (). and in other tutorials.designer. } } } AppDelegate.Drawing. Generally.Mac application instance and passes the name of the class that will handle OS events. when we create an application with multiple windows. we have the FinishedLaunching method. using MonoMac. MainWindowController.Drawing. let’s take a look at the two class-level variable declarations: MainWindowController mainWindowController. public AppDelegate () { } public override void FinishedLaunching (NSObject notification) { mainWindowController = new MainWindowController ().Window . which is responsible for creating our window and listening to OS events: using System. but it’s fairly simple. Main.AppKit. so we can skip any more detail about it for now: using System.NSWindowController [MonoMac.Foundation.Foundation. Apple has created a tool called Interface Builder (IB). This should launch Xcode and look something like the following: . } // Call to load from the XIB/NIB file public MainWindowController () : base ("MainWindow") { Initialize (). } // Called when created directly from a XIB file [Export ("initWithCoder:")] public MainWindowController (NSCoder coder) : base (coder) { Initialize ().AppKit. using System. which allows you to create your UI visually in a designer.Mac integrates fluently with IB. We’re going to examine this in detail later. } // Shared initialization code void Initialize () { } #endregion //strongly typed window accessor public new MainWindow Window { get { return (MainWindow)base.mainWindowController = new MainWindowController ().Foundation. allowing you to create your UI with the same tools that Objective-C users do. using System. using MonoMac. It’s important to note that you don’t have to use IB to create your UI. as they’re just automatically managed by Xamarin Studio and just provide the requisite pluming code that allows access to controls that we add to any window or view in our application.Window. so that any properties on there (as we’ll see later) are available without having to cast it every time you want to access them. MainWindowController.NSWindow [MonoMac.AppKit. Next.Mac application and we have a basic understanding of its components.NSWindowController { #region Constructors // Called when created from unmanaged code public MainWindowController (IntPtr handle) : base (handle) { Initialize ().Generic.Register("MainWindowController")] public partial class MainWindowController { } } We aren’t usually concerned with designer files. using MonoMac.cs As we’ve already seen. Double-click on the MainWindow. the MainWindowController class is our main window’s controller.Collections. namespace Hello_Mac { public partial class MainWindowController : MonoMac. the code tells the main window (the Window property on the controller) that it should be in focus and accept user input (Key). MainWindow. } } } } The Window property is a convenience property that casts the base. Let’s go ahead and walk through how to use IB to define our UI.xib file in Xamarin Studio. you can also build it programmatically.Register("MainWindow")] public partial class MainWindow { } // Should subclass MonoMac.AppKit.Window property to a strongly-typed version of the actual Window class. but it will be automatically populated by Xamarin Studio as we create our UI: namespace Hello_Mac { // Should subclass MonoMac. and appear in the front of any other windows: mainWindowController.cs The designer file for the Main Window class is empty right now.Window. Now that we have created our Xamarin.Linq. Xamarin. That means it’s responsible for the life cycle of the main window.AppKit.MakeKeyAndOrderFront (this). Introduction to Xcode and Interface Builder As part of Xcode.Designer. let’s jump over to Xcode and create our UI. Components of Xcode When you open a Xib in Xcode from MD.If Xcode doesn’t open up. Let’s do a quick overview of Xcode to orient ourselves. Xcode opens with the Navigator Area on the left and the Editor Area in the middle. you can right-click on the file and choose Open With : Xcode. and the Utilities Area on the right: . it will populate. if you select a control (or the main view).xib file is open. IB was a separate application. The Utility Area is further broken down into two sub-areas. In previous versions of Xcode.When a . If you don’t see the Utilities Area. the Editor Area surface is what’s known as Interface Builder (IB). you can make it display by clicking the far-right button in the View section of the toolbar: The Utility Area is mostly empty because nothing is selected. Inspector Tabs and Library Tabs: . however. The Inspector Tabs are kind of like property pages.In the Library Tabs Area. where you can examine and edit control instances in the . you can find controls and objects to place into the designer. We’re going to use IB to create the following: . Bindings Inspector – The Bindings Inspector allows you to configure controls so that their values are automatically bound to data models. View Effects Inspector – The View Effects Inspector allows you to specify effects on the controls. Attributes Inspector – The Attributes Inspector allows you to customize various attributes of the selected control/view. We’ll examine Outlets and Actions in just a moment. the File Inspector shows file information. the Quick Help tab is part of Xcode 4’s redesigned help system. Identity Inspector – The Identity Inspector provides information about the selected control/view. It provides contextual help based on what is selected in Xcode.designer. let’s actually use IB to create the UI of our main view. Size Inspector – The Size Inspector allows you to control the size and resizing behavior of the selected control/view. as shown in the following illustration: From left-to-right. such as the file name and location of the Xib file that is being edited. Connections Inspector – The Connections Inspector shows the Outlet and Action connections of the selected controls. There are 8 different Inspector Tabs. Quick Help – Also new in Interface Builder 4. these tabs are: G G G G G G G G File Inspector – New in Interface Builder 4. Creating the Interface Now that we’re familiar with the Xcode IDE and IB. such as animations. select them and then pull on their resize handles. Double-click on the button to set its text. you’ll notice that IB gives you helpful snap hints that are based on Apple’s Human Interface Guidelines (HIG). the Document Inspector. These guidelines will help you create high quality applications that will have a familiar look and feel for Mac users. 4. As you’re resizing and moving controls around. The Document Inspector is just to the left of the Editor Area and can be expanded by clicking the > arrow button at the bottom of the area: The Document Inspector shows you all of the items in a tree and allows you to select them: &nbsp. let’s look at one other useful area.To create this UI: 1. 3. 2. This will let us update the label with text when the buttons are clicked. . While we have IB open. To resize the controls. Make the label nearly as wide as the view. Drag a Push Button and a Label to the designer from the third tab of the Library. NET UI programming. For example. In order to access our controls from code. this means that in order to create an Outlet or Action.cs file. Actions are powerful and convenient because you can wire up many controls to the same Action. when an Action is performed on a control. etc. so you can do things like attach event handlers. Xamarin Studio will then synchronize the changes to this file with the designer file. This . If you wire up a control to an Outlet. for that matter). this can be a great alternative to using the designer window. Apple gives us two options: G G Outlets – Outlets are analogous to properties. it’s exposed to your code via a property. Outlets + Actions Defined So what are Outlets and Actions? In traditional . OK. More specifically. This is where we’ll use Xcode to define our Outlets.h as part of the Xcode project it generated to use the designer. the control will automatically call a method in your code. In Xcode 4. Outlets and Actions Xamarin Studio created a file called MainWindowController.h file is a stub file that Xamarin Studio created to mirror the Designer. Actions – Actions are analogous to the command pattern in WPF. say a button click. Outlets and Actions are added directly in code via Control-dragging. Simply adding a control to a view doesn’t make it accessible to code.If you have a complicated UI. we need to wire up our Outlets to code. call methods on it. you choose which control element you’d like to . now that we have created our UI. a control in the UI is automatically exposed as a property when it’s added. Things work differently in Mac (and in iOS programming. h file is chosen: . but the process is nearly exactly the same. we won’t use Actions in this application.xib file in the Interface Builder designer. hold down the Control button on the keyboard. this means that you drag into the Objective-C stub files that correspond to the C# file where you want to create the Outlet or Action.add an Outlet or Action.h file at once: Now we can start wiring up our Outlets. In the Assistant Editor. For Xamarin. and the code file in the code editor). In order to view the Assistant Editor split screen. choose the file drop down just above the editor. we first need to make sure that they’re going to get wired up in the right file. In order to facilitate this. and drag that control directly into your code. Xcode 4 introduced a split-view in the Editor Area called the Assistant Editor that allows two files to be visible at once (the . Adding an Outlet Before we start to wire up our Outlets.Mac developers. click the middle button of the Editor choice buttons in the toolbar: Xcode will then show the designer and . and make sure that the MainWindowController. Once we’ve made sure that the right file is chosen. So we’ll get in the habit now. giving you the option to choose either Outlet or Action. but in practice. Hold down the Control key on the keyboard. and then drag from the control to an empty space in your code file after the @interface definition: You can drag from the Document Inspector as well. Determine for which control you want an Outlet. let’s perform the following procedure to create our Outlets: 1. Choose Outlet and name it ClickMeButton: . we’re going to create an outlet for the Click Me button. To start with. A popover will then show. Outlets are should nearly always be put in controllers (where they’ll be used). 2.In this case. we could wire up the Outlets to the window file. which can be helpful if you have a complicated UI with nested controls. and Xcode will insert the appropriate code in the .Click Connect after you’ve filled out the form. and then go back to Xamarin Studio. In the MainWindow.cs file we should now see our new Outlet exposed as a property on the MainWindowController class: .designer.h file: Save the file. h file should have the following Outlets now defined: @property (assign) IBOutlet NSButton *ClickMeButton. First. let’s save the files and switch back to Xamarin Studio to actually do something interesting with them. so let’s switch back over to Xcode. Writing the Code In our application. every time the first button is clicked.AppKit.cs file to expose them to your application. this interface and all its Outlets can be created in just a minute or two. @property (assign) IBOutlet NSTextField *OutputLabel. Create the label’s Outlet the same way we did the button’s Outlet and name it OutputLabel. We need to create one more Outlet for our label. The . Note: It probably took a long time to create the UI and Outlets for our first application.Note that this is a partial class.h file. we need to do two things. Now that we have our Outlets wired up.NSWindowController { protected int .cs file. we need to create a class-level variable in our MainWindowController class to track the number of clicks that have happened: public partial class MainWindowController : MonoMac. As you can see. and then automatically synchronizes those changes in the respective designer. so that Xamarin Studio doesn’t have to edit our MainWindowController. Once you’ve practiced awhile working with IB. but we’ve introduced a lot of new concepts and we’ve spent a lot of time covering new ground. we’re going to update our label to show how many times the button has been clicked. Xamarin Studio listens for changes to the . In order to accomplish this. and it may seem like a lot of work. so let’s make sure that Debug|x86 is selected in the build drop down: Then. we have three options: . If we tried to access the button control before the . Start by confirming that your code (both in Xcode and in Xamarin Studio) matches the code in the tutorial.app (application) file with a bunch of extra metadata that allows us to debug what’s happening while the application is running.Mac application. Whenever we build an application. It’s kind of a strange name but it’s the event that gets raised when the button is clicked.numberOfTimesClicked = 0. }. In our case. or from the Build menu. Let’s build it first. we can choose what kind of build we want: G G G Debug – A debug build is compiled into an . Running the Application To run the application.Activated += (object sender. Also notice that we used the Activated event on the button. … } Next. If there are errors. you’ll see a Build Succeeded message in the status bar of Xamarin Studio. EventArgs e) => { numberOfTimesClicked++.AwakeFromNib (). either press +B. we need to override the AwakeFromNib method and add some code to update our label with the number of times the button was clicked: public override void AwakeFromNib () { base. because AwakeFromNib is called after the OS has loaded the UI from the . or we can build it without running it. review your procedure and make sure that you’ve followed the steps correctly. We can build and run all in one step. we just want a debug build. so now it’s time to run it and test it! Testing the Application It’s time to build and run our application. but it doesn’t include debug information.xib file. so it’s smaller and executes faster. If there are no errors. instead of another method such as Initialize.xib file has been fully hydrated. just to learn how to build without deploying. Release – A release build also creates an .app file. to see it in action and make sure it runs as expected. choose Build All.". AppStore – An AppStore build creates a signed application package that is ready to submit to the App Store. in the same class (MainWindowController). OutputLabel. } We need to use AwakeFromNib. we’d get a NullReferenceException error because the button control would not be created yet. That’s it! We’ve created our first Xamarin.StringValue = "Clicked " + numberOfTimesClicked + " times. ClickMeButton. View. . you’ve now built and run your very first Xamarin.Mac application! Summary Congratulations! We covered a lot of ground here. Controller (MVC) pattern in Mac and how it’s used to create more complex applications. we’re going to take a look at the Model. you should now have a solid understanding of the components of a Xamarin. The application will build (if it hasn’t been built already) and if we click the button a few times.Mac application as well as the tools used to create them. but if you followed this tutorial from start to finish.G G G Press +Enter From the Run menu. choose Debug Click the Gear icon with the green circle from the build toolbar. In the next guide. we should see something like following: Congrats.
Copyright © 2024 DOKUMEN.SITE Inc.