1

macOS Development for Beginners: Part 1

 3 years ago
source link: https://www.raywenderlich.com/731-macos-development-for-beginners-part-1
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Home macOS Tutorials

macOS Development for Beginners: Part 1

In this macOS development tutorial for beginners, learn how to create your first “Hello, World” app with Swift and take a tour of Xcode.

By Roberto Machorro Feb 22 2017 · Article (20 mins) · Beginner

4.9/5 54 Ratings

Version

Update note: Roberto Machorro updated this tutorial for Xcode 11 and Swift 5. Sarah Reichelt wrote the original article.

Do you want to learn how to develop your own apps for macOS?

Good news! Apple makes developing for macOS incredibly easy, and in this tutorial series you’ll learn how. You’ll learn how to create your first app for macOS — even if you’re a complete beginner.

  • In this first part you’ll first learn about how to obtain the tools you need to develop for macOS. Then, while creating a simple “Hello, World!” app, you’ll take a tour of Xcode, discovering how to run an app, edit code, design the UI and debug your code.
  • In Parts 2 & 3 of this series, you’ll create a more complex Egg Timer app and learn about the components that make up a macOS app, from how an app starts, to constructing the UI, all the way to handling user interaction.

So what are you waiting for? The world of desktop apps awaits!

Note: Here’s some guidance of where to begin with this series:

  • If you are new to Swift, this series assumes some Swift knowledge, so first check out our Swift tutorials to get a great introduction.
  • If you already have iOS experience, this first part of the series will be a review. Take a quick look through the topics to make sure and then skip straight ahead to the next part of the series.
  • Otherwise, keep reading. This series is for complete beginners – no experience of developing for iOS or macOS is required!

Getting Started

To become a macOS developer, you will need two things:

  1. A Mac running macOS Catalina: The macOS operating system only runs on Apple computers, so you need a Mac both to develop and run macOS apps.
  2. Xcode: This is the IDE used to create macOS apps. You’ll learn how to install this later in this section.

Once you’ve built your app, if you want to upload it to the App Store for distribution, you’ll also need to pay for an Apple developer account. But this is not a requirement until you are ready to send your app out to the world, and even then, only if you want to distribute through the Mac App Store. If you already have a developer account for distributing iOS apps, then you are all set – Apple has merged the developer accounts so that you only need a single account to distribute apps for any Apple devices.

Unlike some other platforms, developing for macOS requires the installation of just one tool: Xcode. Xcode is an IDE (Integrated Development Environment) that includes everything you need to develop macOS, iOS, watchOS and tvOS apps.

If you don’t have Xcode already, click on the Apple icon in the upper left of your menu and select App Store… to open the Mac App Store. You will need an App Store account to download Xcode even though Xcode is free.

Search for Xcode and click the Install button to start the download. Once it has downloaded and installed (which may take a while – it is quite large) open it from your Applications folder. The first time you run Xcode, and after every major update, it will ask you for permission to install additional components. Enter your password and allow Xcode to install these components.

Hello World!

Following the long-standing tradition when learning a new programming language or platform, you are going to start by creating a Hello World! app for macOS.

Open Xcode if it is not already running. You should see a Welcome to Xcode window – if you don’t see it, choose Welcome to Xcode from the Window menu.

Click Create a new Xcode project and when the next dialog appears, choose macOS from the tabs across the top. Select App from inside the Application section and click Next.

Give your new app a name – HelloWorld – make sure that the language is set to Swift and that Storyboard is selected for user interface. Uncheck all the other options.

Click Next and Create to save your new app project.

Running Your App

Xcode has created the basic template for your app with all the required files. At this stage, it is fun to run the app and see how much you get for free.

Click the Play button in the toolbar to run the app or use the Command-R shortcut. Xcode will now compile all of the code into machine code, bundle up the resources required by the app and then execute it.

Run

Note: The first time you ever build and run an app in Xcode, you might be asked whether you want to Enable Developer Mode on this Mac. You’re safe to select Enable, at which point you may have to enter your password. Developer mode allows Xcode to attach a debugger to running processes – which will be extremely useful when building your application!

You should now see a blank window but don’t be disappointed – have a look at what you can already do:

  • The window is resizable, it can be minimized and made full screen.
  • There is a complete set of menus, many of which already work without you doing anything.
  • The Dock icon has the usual menus.

FirstRun

But now it’s time for you to make the display a bit more interesting, so quit the app and go back to Xcode.

The Xcode Interface

Xcode packs a lot of features into a small package, so not everything is visible at one time. To be an efficient Xcode user, you need to know where everything is — and how to get to it.

When you open a new project in Xcode, you have a window with a toolbar and three main panels.

The left panel is the Navigator panel and has 9 display options across the top. The one you will mostly use is the first one – Project – which lists all the files in your project and allows you to click on any one to edit it.

The center panel is the Editor panel and will display whatever you have selected from the Project Navigator.

The right panel is the Utilities panel and it will vary depending on what you are looking at in the Editor panel.

Adding the UI

You design the user interface using a Storyboard. Your app already has a storyboard, so go to the Project Navigator and click on Main.storyboard to show it in the Editor panel.

Your display has just changed dramatically! In the Editor panel, you can now see the Document Outline and the visual editor for the UI.

Have a look at the things you can see in the visual editor. There are three main areas, each of which also has a textual representation in the Document Outline:

  • Application Scene: The menu bar and items.
  • Window Controller Scene: Configures how the window will behave.
  • View Controller Scene: Where your UI elements will go.

In the Utilities panel, you see a top section with 9 tabs.

The bottom section switches between various things you can insert into your project. Right now you want to insert UI elements, so select the Object library which is the third from the left.

In the filter at the bottom, type “text” to reduce the number of choices, and drag a Text Field into your View Controller Scene.

Now filter for “button” and drag a Push Button into the View Controller Scene. Finally, add a Label.

Now, build and run the app using the Play button or Command-R. You will see these 3 UI elements. Try typing in the text field – it already supports all the standard editing shortcuts: copy, paste, cut, select all, undo, redo and so on. But the button does nothing, and the label just shows “Label”, so it is time to make things more interactive.

Run2

Configuring the UI

Go back to Main.storyboard and click on the button to select it. In the Utilities panel on the right, make sure the Attributes Inspector is showing – the 5th button across the top. Change the title of the button to “Say Hello”.

Now click in the text field to select it. For this app, the user is going to type their name in here, and when they click the button, the app will show “Hello name-goes-here!” in the label. To help the users, add some placeholder text to the text field using the Attributes Inspector.

Stretch the text field out a bit to allow for long names and position the button to the right of it. When dragging objects around in the View Controller Scene, blue lines will appear to help you align and position the objects based on Apple’s Human Interface Guidelines.

Position the label below the text field and button. Since the label is going to be important, make it use a larger font. Select the label and in the Attributes Inspector, change the font to System Regular 30.

How about making the text red to add even more excitement?

You can’t tell how long a name a user might enter, so resize the field to fit the height of that font and to almost fill the width of the window.

Build & run the app to check that your UI changes have taken effect. Once you are happy with the look of the text in the label, delete the label’s Title so that the label starts off empty.

RunWithUI

Connecting the UI to the code

Your app still doesn’t do what you want, but in order for that to work, you need to start adding code and that code has to be able to communicate with the UI. To make those linkages, you are going to use Xcode’s Assistant Editor. With the Main.storyboard visible, option-click on ViewController.swift in the Project Navigator. This will create a second editor panel containing the ViewController code.

Depending on the size of your monitor, things may be looking a bit cramped now, so use the rightmost button in the Toolbar to hide the Utilities. If you need even more space, hide the Navigator.

Select the text field. Hold down the Control key and drag from the text field into the top of the ViewController class definition. Let go and enter nameField in the name box of the popup, then click Connect.

Do the same with the label, naming it helloLabel.

Looking at the code that Xcode has generated, you see that these are both marked with @IBOutlet. This is short for Interface Builder Outlet and is how you tell the storyboard editor that these object names are available for linking to a visual object.

For the button, the code does not need to have a name for it, but it does need to know when a user clicks the button. This calls for an @IBAction instead of an @IBOutlet.

Select the button and Control-Drag into ViewController.swift as before. This time, change the Connection popup to Action and set the name to sayButtonClicked. This creates the function that will be called when the button is clicked.

Everything is now in place to edit the code. Close the Assistant Editor using the X in the top left corner and switch to ViewController.swift. If you had hidden the Navigator, click the toggle button in the top right, or press Command-1 to jump directly to the Project Navigator.

Enter the following code into sayButtonClicked.

var name = nameField.stringValue
if name.isEmpty {
  name = "World"
}
let greeting = "Hello \(name)!"
helloLabel.stringValue = greeting

The complete code in ViewController.swift now looks like this. The blobs beside the line numbers indicate a connection to the interface in the storyboard.

Build and run the app.

Click the Say Hello button without entering anything and you will see “Hello World!”. Now type in your name and click the button again to see your own personal greeting.

HelloWorld

Debugging

Sometimes, we programmers make mistakes – hard to believe I know, but trust me, it happens. And when it does, we need to be able to debug our code. Xcode allows us to stop the code at any point and step through line by line, checking the values of the variables at each point so that we can find the error.

Go to sayButtonClicked in ViewController.swift and click on the line number beside the var name = line. A blue pointed rectangle will appear. This is an active breakpoint and when you click the button, the debugger will stop here. Click it again and it will turn pale blue. It is now an inactive breakpoint and will not stop the code and start the debugger. To remove the breakpoint completely, drag it out of the line numbers gutter.

Add the breakpoint again and run the app. Click the Say Hello button. Xcode will come to the front with the breakpoint line of code highlighted. In the bottom of the Editor panel, there will now be two new sections: Variables and Console. The Variables section shows the variables used in this function as well as self – the View Controller, and sender – the button.

Above the Variables display is a set of buttons for controlling the debugger. Mouse over each one and read the tooltip to see what it does. Click the Step Over button to move to the next line.

In the Variables display, you can check that name is an empty string, so click Step Over twice more. The debugger will move into and through the if statement and set the name variable to “World”.

Select the name variable in the Variables display and click the Quick Look button below to see the contents. Now click the Print Description button to see the information printed in the Console. If the “World” value had not been set correctly, you would have been able to see that here and work out how to fix your code.

When you have checked the contents of the name variable, click the Continue program execution button to stop debugging and let the program move on. Use the button in the top right to hide the Debug area.

Images

In addition to code and user interfaces, your app will also need some artwork. Due to the different screen types (Retina and non-Retina), you often need to provide multiple versions of each asset. To simplify this process, Xcode uses Asset Libraries to store and organize the assets that accompany the app.

In the Project Navigator, click on Assets.xcassets. The only item there so far is AppIcon which will contain the various images needed to display the app icon in all the required resolutions. Click on AppIcon – you can see that it wants 10 different images to cover all the possibilities, but if you supply any one of these, Xcode will use it as best it can. This is not good practice, as you should supply all the required icon sizes, but for this tutorial one icon will be sufficient.

Download the sample icon which is a 512 x 512 pixel image. Drag it into the Mac 512pt 1x box.

Build and run the app to see the icon in the Dock menu. If you still see the default app icon, quit the HelloWorld app, go back to Xcode and choose Clean Build Folder from the Product menu, then run the app again.

DockIcon

Getting Help

As well as being an editor, Xcode also contains all the documentation you will need for writing macOS apps.

Go to the Help menu and choose Developer Documentation. Search for NSButton. Make sure Swift is the selected language, then click the top search result so that you can read all the details about buttons and button properties.

There is also a way to get to relevant documentation directly from your code. Go back to ViewController.swift and find the first line in sayButtonClicked. Option-click on the word stringValue. A popup appears with a short description. At the bottom of the popup is a link to Property Reference. Click this link and the documentation will open to show more information.

Option-clicking is often a really good way to learn, and you can even add documentation to your own functions so that it shows up in the same way.

The Help menu also includes Xcode Help for specific information about the Xcode environment.

Where to Go From Here?

In the next part of this tutorial series, you will start to create a more complicated app. Hope to see you there!

If you have any questions or comments on this tutorial series, please join the discussion below!

raywenderlich.com Weekly

The raywenderlich.com newsletter is the easiest way to stay up-to-date on everything you need to know as a mobile developer.

Get a weekly digest of our tutorials and courses, and receive a free in-depth email course as a bonus!

Average Rating

4.9/5

Add a rating for this content

Sign in to add a rating
54 ratings

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK