This article has been translated from Raywenderlich.com’s classic MacOS development tutorial. You can translate up to 10 articles on Raywenderlich.com. Translating it is just because the dormitory is too noisy and hot. Only in this way can I finish reading one sentence by one and take my notes. I hope you can read the English original if you have English reading ability, after all, whether Xcode, or official documents, or all kinds of cutting-edge information are only in English version.

This article focuses on the development of zero-based applications for MacOS, including the following

Do you want to learn how to develop your own MacOS app? I have some good news for you! As you’ll find in this tutorial, Apple makes developing MacOS apps incredibly easy. You’ll learn how to create your first MacOS app — even if you’re a complete novice.

  • In Part 1, you’ll learn how to get the tools you need for MacOS development. Then, by creating a simple “Hello, World!” App, you’ll get a rough idea of Xcode — how to run an app, edit code, design UI, and debug your code.
  • In the second and third parts, you’ll create a much more complex “Egg Timer” app and learn about the various components of a MacOS app — from how an app is launched, to how the UI is built, to handling interactions.

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

Note: Here are some tips on how to start learning this series:

  • If you’ve never studied Swift before, this series covers some SWIFT knowledge, so check out our SWIFT tutorial first.
  • If you’ve had some iOS development experience, this first section can be seen as a refresher. To be on the safe side, take a quick look at these and jump straight to the next section.
  • This course is for the complete novice – you don’t need to have any iOS or MacOS development experience!

start

To become a MacOS developer, you need two things:

  1. A Mac running MacOS Sierra: The MacOS operating system only runs on Macs, so you’ll need a Mac to develop and run MacOS apps.
  2. Xcode: This is the IDE (Integrated Development Environment) for creating MacOS apps. You will learn how to install it on your Mac later.

When you’ve finished developing your app and want to upload it to the App Store for sale, you’ll need an Apple developer account. But it’s not a requirement until you’re ready to let your app fly around the world. Even if you’ve decided to release your app, you’ll only need a developer account if you’re ready to sell through the Mac App Store. If you’re already an iOS developer, you’re all set — Apple has consolidated various developer accounts into one, so you only need one account to distribute apps to a variety of Apple devices.

Unlike some other platforms, developing apps for MacOS requires only one tool: Xcode. Xcode is the IDE that contains everything you need to create MacOS, iOS, watchOS, and tvOS apps.

If you haven’t already installed Xcode, click on the Apple icon in the upper left corner of your Mac and selectApp StoreTo open the App Store. Even though Xcode is free, you still need an App Store account to download Xcode.

Now search for Xcode and clickTo obtainButton to start the download. Once it’s downloaded and installed (which may take a while, it’s not a small piece of software), you can check it out atThe applicationOpen it in the folder.

Hello World!

Following the long tradition of learning a new programming language or platform, you will learn how to develop a “Hello World!” for MacOS. The app.

If Xcode is not already open, please open it. You’ll see a “Welcome to Xcode” window. If you don’t see this window. Click Welcome to Xcode on the Window menu.

Click on theCreate a new Xcode projectIn the following dialog box, select it in the TAB at the topmacOSAnd then inApplicationSelect in partCocoa ApplicationAnd click theNext.

Give your app a name —Hello WorldAnd to ensure thatLanguageSet toSwift, as well asUse StoryboardsBe checked. Uncheck all other options.

Click Next and Create to save your new project.

Run your app

Xcode has applied a basic template to your app and added all the files it needs to run. So it’s kind of fun to just run it without doing anything.

Click on the toolbarPlay button ▶️Or use keyboard shortcuts⌘ RTo run your app. Xcode will now compile all the code into machine language, package all the resource files the app needs to run, and then run it.

Note: The first time you run an app in Xcode, you may be asked if you want to Enable Developer Mode on this Mac. Please feel free to click Enable Developer Mode. This may require you to enter your Mac’s boot password. Developer mode allows Xcode to attach a debugger to your app’s process — extremely useful for developing an app!

You should now be able to see a blank window, but don’t lose heart — here’s what you can do:

  • The window can be resized, minimized, and full screen;
  • The app already has a complete set of menu options, many of which can be used without you having to do anything.
  • The app icon on the Dock also has the usual menu.

But now it’s time to make this empty screen a little more interesting, so please exit the app and return to Xcode.

Xcode interface

Xcode combines many functions in the same window, so many things can’t be displayed at the same time. To be an Xcode pro, you need to know where the features you need are and how to turn them on.

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

The left window is the Navigator, which is divided into eight sections by eight tabs at the top of the panel. The one you’ll use most often is the first one — Project — which lists all the files in your Project that you can edit by clicking on them. The middle panel is the Editor, which shows the files you selected in the Project Navigator. The panel on the right is the Utilities panel, which displays content that changes depending on what you do in the Editor.

Add the UI

You can use storyboards to design your app’s UI (user interface). Your app already has a storyboard, so click Main.stroyboard in the Project Navigator to display it in the editor. Your screen switches automatically, isn’t it amazing! In the editor, you can now see a wireframe of the document, as well as a visual UI editor. Take a look at what’s in your visual editor. There are three main areas, each with a text placeholder:

  • Application Scene: Menu bar at the top;
  • Window Controller Scene: Configure how the Window will behave;
  • View Controller Scene: Where to put the UI controls.

inUtilitiesIn the panel, you will see eight tabs in the top half and four tabs in the bottom half

The lower half of the area presents things that you can insert into your project. Now you need to insert the UI control, so click on the third iconObject Library.

In the filter at the bottom (input box), type “text”, then find and drag oneText FieldTo yourView Controller Scene.

Now search for “button” and drag onePush ButtonView Controller SceneIn the. Finally, add one moreLabel.

Now, clickPlay button ▶️Or press the⌘ RTo compile and run your app, you can see these three UI elements. Try typing something in the input field – it now supports all the standard keyboard shortcuts: Copy, Paste, Cut, Undo, Redo… But the buttons on the screen still don’t do anything and the text just shows a “Label”, so now it’s time to join them together.

Configure the UI

returnMain.storyboardAnd click the Button on the screen, on the rightUtilitiesIn the panel, click on the fourth TABAttributes Inspector.

Change the title of the button to “Say Hello”. The button may not be wide enough at this point, so click on the menu barEditor, and clickSize to Fit Content. (If the Size to Fit Content option is not available, click in the space to deselect the button, reselect it, and try again.)

Now click and select the Text Field. In this app, the user will enter their name here, and when they click the button, the app will show “Hello” + their name. So just to remind the user, let’s do thisAttributes InspectorAdds a placeholder to the input box in.

Drag the input box a little larger to fit some of the longer names, and drag the button to the right of it. When you are inView Controller SceneWhen you drag an element, blue dotted lines appear to help you align and place the elements according to Apple’s Human Interface Guidelines.

Place the Label below the input box. Because this Label is very important, let’s make it a little bigger, select this Label, onAttributes InspectorIn theFontChange toSystem Regular 30.

How about something more exciting! Change the color of the text to red.

You don’t know how long the user’s name will be, so we need to resize the input field to fit the height of the font and adjust the width to be about the same as the width of the window.

Compile and run your app to check that your UI Settings are working. Once you are satisfied with the text on the Label, change the Label’sTitleDelete, which clears the text inside the Label.

Connect the UI to the code

Your app doesn’t work the way you expect it to right now, you still need to add code to make your code talk to the UI. In order to make this connection, you need to use XcodeAssistant Editor, select it in the navigatorMain.storyboard, and click while holding down the Option⌥ keyViewController.swiftThis will open the second editor panel for ViewController.swift without closing the previously opened file.

Depending on the size of your monitor, things on the screen first may seem a bit crowded, so hide the Utilities panel by clicking on the top right button of the toolbar. If you still don’t have enough space on your monitor, hide the Navigator panel altogether.

Select the input field, hold down the Control⌃ key and drag the text field toclass ViewController : NSViewController {override func viewDidLoad() {When you release the mouse, a small window pops up and type in “Name”nameField, and clickConnect.

Do the same thing for the Label and name ithelloLabel.

Take a look at Xcode’s auto-generated code, and you’ll see that it all starts with@IBOutletTo begin with, this is short for “Interface Builder Outlet,” which tells the Storyboard editor how the names of these objects are associated with visual elements.

For that button, the code doesn’t need to give it a name, but it does need to know when the user clicked the button. with@IBActionNo, this connection is called@IBAction.

As before, select the button, hold down the Control⌃ key and drag the text box toViewController.swiftIn the. This timeConnectionOptions set toActionAnd put thenameSet tosayButtonClicked. This will create a function that will be called when the button is shocked.

Now everything is ready except the code! Close the Assistant Editor by clicking the ‘×’ in the upper right corner of the right Editor pane and go back to ViewController.swift. If you have hidden the Navigator, click the button in the upper right or press ⌘1 to jump directly to the Project Navigator. Enter the following code into the sayButtonClicked function:

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

After removing the automatically generated copyright information at the top, it is finishedViewController.swiftThe code in should look like the screenshot below. The small bubble to the left of the line number indicates that this is the connection point between a Stroyboard and the interface.

Now compile and run your app.

Type nothing and clickSay HelloButton, and you will see “Hello World!” ; Enter your name and then click to see your own greeting.

debugging

Sometimes, we developers make mistakes — and trust me, we do. When we make a mistake, we need to debug our code. Xcode allows you to pause at any point in the code and then run the code line by line, allowing you to check the values of variables after each line to find errors.

inViewController.swiftFound in thesayButtonClicked, click on thevar name =The line number on the left, a little blue flag will appear, which is an activated breakpoint, where the debugger will pause the application when you click on the button in your app’s interface. Click it again and it will turn a light blue, which is an inactive breakpoint that will not pause the code and will not start the debugger. To remove a breakpoint completely, drag it out of the line number column.

Add another breakpoint and run your app, clickSay HelloButton, Xcode will move to the top and highlight the line with the breakpoint. inEditorAt the very bottom of the panel, there will be two sections:Variablesand3. Console.VariablesSection shows all the variables used in this function as well asself(i.e. View Controller) andsender(that is, buttons).

inVariablesAt the top of the section are several buttons that control the debugger. Place your mouse over each of these buttons and follow the pop-up tooltips to see what they do. Click on theStep OverButton to run the next line of code.

inVariablesSection, you can seenameIs an empty string, so keep clickingStep OverButton twice, the debugger will move toifStatement, and putnameSet the variable to “World”.

inVariablesSelect in sectionNameVariables, click on the bottomQuick LookButton to view the specific content, electric shockPrint DescriptionPress to output its information toConsoleIn part. If the “World” is not set correctly, you should be able to see it here and figure out what to do about it.

When you have checked the contents of all the variables, click the Continue Program Execution button to stop debugging and let the program Continue. You can hide the debugger by using the buttons in the upper right corner of the screen.

image

In addition to the code and UI, your app needs some graphics. Depending on the screen (Retina display and non-Retina display), you often need to provide multiple versions of a set of assets. To simplify the process, Xcode usesAsset LibrariesTo store and manage the assets needed by these apps.

inProject NavigatorClick on theAssets.xcassets, so far there’s only oneAppIcon, which contains ICONS of apps in different resolutions. Click on theAppIcon, you will see that it takes 10 different pictures to take care of all of the situation, but if you only provide a, so the Xcode will try to make it the best effect, but this is not a right way for your app – you need to do our best to provide all the size of the icon, but in this tutorial, we only prepared an icon.

Download 512×512 pixelsSample iconI’m going to drag it toMac 512pt 1xIn the box of.

Compile and run your app. Check the icon in the Dock bar. If you still see the default icon, please click theProductFrom the menuClean“And then run again.

To get help

In addition to an editor, Xcode includes all the documentation you’ll need to write MacOS apps.

inHelpFrom the menuDocumentation and API Reference. searchNSButton, please make sure that the language is currently selected is Swift, and just click the search results at the top to find all the information about the button.

There’s also a way to look directly at the relevant documents in your code, go back to viewController.swift, find the row where sayButtonClicked sits, hold down Option⌥ and hit StringValue. A quick query panel will pop up. There is also a link to Property Reference at the bottom, which you can click to see more information in the documentation. Option⌥ + mouse click is a particularly good way to learn, and you can even add your own documentation to your own functions for quick reference later. The Help menu also includes the Xcode Help, where you can learn more about Xcode.


Next Party: Zero Base MacOS Application Development (II)?