If you need to run one type of animation after another in macOS, Swift provides a simple way to do this where the code looks like this:
By itself, this runAnimationGroup code does nothing. What you need to do is put your animation code within the first set of curly brackets and when that first animation completes, then you can run a second set of animation if you wish.
Suppose you want to rotate an item such as a label and when it’s done rotating, flip it back to its original position. First, create a label and an IBOutlet such as:
Once you have an IBOutlet to represent a label on the user interface, you can rotate it using this code:
Thea love code takes five seconds to rotate a label (lblMessage) 45 degrees. When it’s completed, it changes the label’s rotation back to 0 again.
While this simple example shows how to rotate an item, the more important lesson is to see how the runAnimationGroup lets you combine two different types of animations where the second animation runs after the first animation completes. Any time you need to run two different types of animation back to back, use the runAnimationGroup structure.
Posted in Algorithms, macOS
If you want to make an item on the user interface appear to fade away and reappear again, you can use something called the animator() method. Essentially all you have to do is create an IBOutlet for a user interface item (such as a button or label) and then apply the animator() method along with defining the alphaValue property to 0 (completely invisible) or 1 (completely visible).
Of course, if you assign a user interface item’s alphaValue property to 0, it will suddenly disappear, so that’s why you need to create a delay effect using the following code:
This simply tells code to delay the animator() action by three seconds (or whatever number you assign to the duration property.
Create a simply macOS project using storyboards and place a label and a push button anywhere on the view. Create IBOutlet for the label like this:
Now create an IBAction method for the push button (call it AnimateMe) and fill it with Swift code such as:
This code simply checks what the alphaValue of the label might be. If its value is 1 (completely visible), then it slowly fades the label away in three seconds and sets its alphaValue property to 0. This creates a gradual fade out visual effect.
If the label’s alphaValue property is already 0, then the above Swift code takes three seconds to slowly set the alphaValue to 1, which creates a fade in visual effect.
Obviously there’s more to animation using the animator() method but this can get you started in seeing how simple it can be to create animation in a macOS program.
Posted in Algorithms, macOS, User Interface
One of the reasons why artificial intelligence (AI) failed during the early days was because it required humans to program intelligence into a program. That meant exhaustively writing instructions for every possible outcome.
One of the earliest and more limited successes of AI were expert systems that consisted of a series of if-then rules to mimic the thinking process of a human expert. The reason why expert systems worked was because they could tackle a narrow niche with limited and known variables. The reason why expert systems ultimately failed is because they couldn’t advance beyond narrow niches and required humans to exhaustively write if-then rules for every possibility.
Even worse, when conditions changed, human programmers had to go back into the expert system to reprogram it and update it. This constantly meant consulting with a human expert and a human programmer, which made the expert system cumbersome to modify to the point where it wasn’t worth it at all.
That’s all changed with machine learning. The whole idea behind machine learning is to let a program teach and update itself. Not only is this far faster, but it’s far more accurate allowing the program to adapt to changing conditions. If you’re interested in machine learning with Swift, download the open source, Swift AI library.
This Swift AI library lets you create neural networks for both macOS and iOS. By incorporating machine learning in your apps, you can create more adaptive video games or smarter programs that can recognize handwriting or user behavior.
Trying to create machine learning tools on your own in Swift is possible, but clumsy. It’s so much easier to use a tested machine learning framework instead, so that’s why you might want to experiment with Swift AI.
As Swift gains popularity, it’s likely that others will create machine learning frameworks for Swift but until that day comes when we can choose from a variety of machine learning tools, Swift AI offers the best way to experiment with machine learning using Swift.
At the very least, dig through the sample programs in the Swift AI library and give yourself a rudimentary understanding of how machine learning works and how to implement it in Swift.
To download the Swift AI library for adding machine learning to iOS and macOS programs, click here.
Posted in Algorithms, iOS, macOS
In any programming language, you can choose arbitrary names for your functions and parameters. For example, you could create a completely valid but confusing function like this:
Notice that the function name (x239) and parameter name (jke) provides no clue what they do. Although this code is perfectly valid, it’s confusing so it’s always best to choose descriptive function names and parameter names such as:
This function name (printGreeting) and parameter name (name) is much clearer as to the functions purpose, which is to take a name and print a greeting. Of course, this function could actually calculate a differential equation so it’s generally best to choose descriptive function and parameter names that actually describe the purpose of the function.
To call this function, you could use code like this:
The function call uses the printGreeting name and identifies the name (“Sam”). This is perfectly fine but in Swift, you have the option to use external parameter names. This means you can have two parameter names, an external and an internal parameter name.
The internal parameter name is what the function actually uses while the external parameter name is what you use to call the function. So to make the function call read more like an actual sentence, you could use an external parameter name like this:
Notice that the function uses “name” as a variable for the actual code, but when you’re calling the function, you use the external parameter name like this:
Now the function call reads like a complete sentence such as “Print greeting for Sam.”
You may not want to do this for your own function declarations and calls, but you’ll find that many Swift API calls use external parameter names specifically to make function calls seem more like a sentence, typically using external parameter names of “in,”, “for”, and “with”.
External parameter names simply help make code more readable although at the expense of also making function declarations more cumbersome to write. You can choose to use external parameter names or not, but whether you use them or ignore them, you’ll at least better understand why so many of Apple’s API functions look the way they do using external parameter names.
Posted in Algorithms, iOS, macOS
When working with storyboards in a macOS project, you may want to change the background color of a scene (view). The simplest way to do that is to use this command:
This simply assigns the color blue (or whatever value you want to insert there such as red or yellow) to the background of the view layer. Of course, writing specific color values into code isn’t very efficient because if you want to change the color, you have to rewrite the code for a new color.
A far better solution is to change the color using code and the simplest way to do that is to assign the backgroundColor of a view to a variable that represents a different color. One way to do this is to use the Color Panel (see this blog post covering the Color Panel).
So if you create a simple macOS project that uses storyboards, place a push button on the view controller and create an IBAction method with a name such as changeBKColor. Declare a color panel underneath the class ViewController line like this:
Now inside your IBAction method, add code like this:
You’ll need to create a changeColor function like this:
If you run this program, a window will appear with a push button. Clicking the push button will run the IBAction method changeBKColor, which displays a color panel. Choosing a color from this color panel then changes the background of the view. The complete code in the ViewController.swift file should look like this:
Posted in Algorithms, macOS
Chances are good you’ll need to manipulate numbers. However, when you want to display those numbers as a text string to display in a label or text field, you’ll need to convert that number into a string.
The simplest way to convert a number into a string is to use the \( ) method inside quotation marks where you put the number inside the parentheses such as:
In the above example, the “stringHere” variable holds the text string “This is a string = 2.3094”. While this is fine, another method is to actively convert the number into a string by using String( ) where the number goes inside the parentheses such as:
This code works exactly like the previous code so the “stringHere” variable holds the text string “This is a string = 2.3094”. Either method is fine, but there’s a third way to convert numbers into strings and that’s to use the NumberFormatter class.
Some advantages of the NumberFormatter class include:
- Letting you define how many decimal places to display
- Letting you define whether to round up or down
- Letting you work with different number formats such as currency
To use the NumberFormatter class, you need to create an object such as:
Now you can specify the maximum number of decimal places you want to include. If you wanted to display two decimal places, you could use the following:
Once you’ve defined the maximum number of decimal places to display, you can also choose a rounding mode such as one of the following:
- down – always rounds down
- up – always rounds up
When rounding down to two decimal places, a number like 2.3094 would turn into 2.30.
When rounding up to two decimal places, a number like 2.3094 would turn into 2.31.
To define how to round numbers, you could use this code:
To retrieve a string from a number, you must use a number of the NSNumber data type such as:
Now you’ll be able to convert a number into a string using this command:
So the whole code would look like this:
Copy and paste this code into a Swift playground to see how the NumberFormatter class works to convert a number into a string. While using the NumberFormatter class might seem clumsier, it does give you more control over the decimal places to display and how to round a number.
What makes the NumberFormatter class even more useful is that it can convert numbers into one of the following:
- currency – displays the local currency symbol with the number
- ordinal – displays numbers like 2nd or 8th
- percent – displays numbers with a % sign at the end
- spellOut – types the text of the number such as “two point three zero nine four”
If you wanted to display a decimal as $2.31, you could use this code:
If you wanted to display a decimal like 2nd, you could use this code:
If you wanted to display a decimal like 230.94%, you could use this code:
Finally, if you want to display a decimal like “two point three zero nine four” you could use this code:
For simple conversion of numbers to strings, it’s much simpler to use either the \( ) or String( ) methods, but if you need unique formatting, then use the NumberFormatter class instead.
Posted in Algorithms
If you’re creating a macOS program using storyboards, you may need to know the size of a window. To get this information, you just need to follow two steps:
- Create an IBOutlet that represents your window. This IBOutlet should be of the type NSView
- Use the frame.width and frame.height properties to get the width and height of the window defined by your IBOutlet
To create an IBOutlet for a window, just opens he Assistant Editor, move the mouse pointer over the window, and Control-drag to the Swift class file linked to your window such as ViewController.swift. Then release the Control key and the left mouse button to create an IBOutlet.
You can use any name for your IBOutlet, but whatever name you choose will now represent your window such as:
Assuming you named your window IBOutlet myWindow, you’ll be able to access the frame.width and frame.height properties like this:
If you put the following two lines of code in the viewDidLoad function that runs as soon as a window appears, you’ll see the defined width and height of the window.
Posted in Algorithms, User Interface
If you’re creating a macOS program and need to identify the screen resolution of a Macintosh, you can get the height and width of the screen resolution by using the following code:
First you need to create a variable to represent the main screen (NSScreen.main()). Then you need to create a second variable (let resolution = myScreen?.frame) to identify the frame of the screen.
Now you can retrieve the width and height of the screen frame using the size.height and size.width properties. The above code uses the print command to retrieve the screen height and width but you could easily just store these values in a variable for your own program to use.
Posted in Algorithms, macOS
Swift contains four built-in founding functions:
- round – Rounds up from 0.5 and higher and rounds down from 0.49 and lower
- floor – Rounds to the lowest integer
- ceil – Rounds to the highest integer
- trunc – Drops the decimal value
To see how these different rounding function is work, just copy this Swift code into a Swift playground so you can see them in action:
However, if you want to round decimal numbers to a fixed number of decimal places, you may find the following function handy:
To use this function, you just need to define the number you want to round and the number of decimal places to display such as:
This Swift code would display three decimal places such as 18.178. Any time you need to round numbers to specific decimal places, add the roundToPlaces function to your own code.
To learn more about different rounding functions, click here.
Posted in Algorithms
The Cocoa framework contains standard panels your programs can use to Open, Save, or Print a file. Of course, you have to write code to make those panels work, but the Cocoa framework provides the code to display standard panels for your program to use.
One panel you can use is the Color Panel, which displays different colors for the user to choose from. To create a panel, you must first define a constant to represent that panel. For a color panel, the code needs to use the NSColorWell class like this:
Next, you need to actually display that color panel using the activate command:
Once you’ve activated the color panel to display it, you need to retrieve the color value the user chooses. To do that, you need to use the action and #selector commands to run the changeColor function like this:
You must write your own code in the changeColor function to make it actually do something. Assuming you have a label on your user interface called myLabel, you could change the label’s textColor property by retrieving the color panel’s color property like this:
So if you put a push button and a label on a window, clicking the push button would display the color panel. When the user chooses a color, the label’s text color would change. The complete code would look like this:
The main key to using the color panel is to call the changeColor function and add your own code to the changeColor function to make it do something.
As you can see, by using standard panels in your macOS programs, you can easily create a macOS program that looks and behaves like a regular macOS program without needing to write hardly any code.
Posted in Algorithms, macOS, Xcode