Category: Algorithms

March 13th, 2017 by admin

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:

        NSAnimationContext.runAnimationGroup({ (context) -> Void in
               // First animation code here
        }, completionHandler: { () -> Void in
              // Second animation code here          
        })

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:

@IBOutlet weak var lblMessage: NSTextField!

Once you have an IBOutlet to represent a label on the user interface, you can rotate it using this code:

    @IBAction func animateMe(_ sender: NSButton) {
        NSAnimationContext.runAnimationGroup({ (context) -> Void in
            context.duration = 5
            lblMessage.animator().frameRotation = 45
        }, completionHandler: { () -> Void in
            self.lblMessage.animator().frameRotation = 0
        })
    }

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

March 6th, 2017 by admin

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:

NSAnimationContext.current().duration = 3

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:

@IBOutlet weak var lblMessage: NSTextField!

Now create an IBAction method for the push button (call it AnimateMe) and fill it with Swift code such as:

    @IBAction func animateMe(_ sender: NSButton) {     
        if lblMessage.animator().alphaValue == 1 {
            NSAnimationContext.current().duration = 3
            lblMessage.animator().alphaValue = 0
        } else {
            NSAnimationContext.current().duration = 3
            lblMessage.animator().alphaValue = 1
        }
    }

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

February 18th, 2017 by admin

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

February 3rd, 2017 by admin

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:

func x239(jke: String) {
    
}

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:

func printGreeting(name: String) {
    
}

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:

func printGreeting(name: String) {
    print ("Hello there, \(name)")
}

printGreeting (name: "Sam")

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:

func printGreeting(for name: String) {
    print ("Hello there, \(name)")
}

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:

printGreeting (for: "Sam")

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

January 23rd, 2017 by admin

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:

self.view.layer?.backgroundColor = NSColor.blue.cgColor

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:

let colorPanel = NSColorWell()

Now inside your IBAction method, add code like this:

    @IBAction func changeBKColor(_ sender: NSButton) {
        colorPanel.activate(true)
        colorPanel.action = #selector(changeColor)
    }

You’ll need to create a changeColor function like this:

    override func changeColor(_ sender: Any?) {
        self.view.layer?.backgroundColor =  colorPanel.color.cgColor 
    }

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:

import Cocoa

class ViewController: NSViewController {

    let colorPanel = NSColorWell()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    @IBAction func changeBKColor(_ sender: NSButton) {
        colorPanel.activate(true)
        colorPanel.action = #selector(changeColor)
    }

    override func changeColor(_ sender: Any?) {
        self.view.layer?.backgroundColor =  colorPanel.color.cgColor 
    }

}

Posted in Algorithms, macOS

January 20th, 2017 by admin

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:

let aDecimal = 2.3094

var stringHere : String

stringHere = "This is a string = \(aDecimal)"

print (stringHere)

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:

let aDecimal = 2.3094

var stringHere : String

stringHere = "This is a string = " + String(aDecimal)

print (stringHere)

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:

let formatMe = NumberFormatter()

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:

let formatMe = NumberFormatter()
formatMe.maximumFractionDigits = 2

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:

let formatMe = NumberFormatter()
formatMe.maximumFractionDigits = 2
formatMe.roundingMode = .up

To retrieve a string from a number, you must use a number of the NSNumber data type such as:

let aDecimal : NSNumber = 2.3094

Now you’ll be able to convert a number into a string using this command:

formatMe.string(from: aDecimal)!

So the whole code would look like this:

let aDecimal : NSNumber = 2.3094

var stringHere : String

let formatMe = NumberFormatter()
formatMe.maximumFractionDigits = 2
formatMe.roundingMode = .up

stringHere = "This is a string = " + formatMe.string(from: aDecimal)!

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:

let aDecimal : NSNumber = 2.3094

var stringHere : String

let formatMe = NumberFormatter()
formatMe.maximumFractionDigits = 2
formatMe.roundingMode = .up

formatMe.numberStyle = .currency
stringHere = "This is a string = " + formatMe.string(from: aDecimal)!

If you wanted to display a decimal like 2nd, you could use this code:

let aDecimal : NSNumber = 2.3094

var stringHere : String

let formatMe = NumberFormatter()
formatMe.maximumFractionDigits = 2
formatMe.roundingMode = .up

formatMe.numberStyle = .ordinal
stringHere = "This is a string = " + formatMe.string(from: aDecimal)!

If you wanted to display a decimal like 230.94%, you could use this code:

let aDecimal : NSNumber = 2.3094

var stringHere : String

let formatMe = NumberFormatter()
formatMe.maximumFractionDigits = 2
formatMe.roundingMode = .up

formatMe.numberStyle = .percent
stringHere = "This is a string = " + formatMe.string(from: aDecimal)!

Finally, if you want to display a decimal like “two point three zero nine four” you could use this code:

let aDecimal : NSNumber = 2.3094

var stringHere : String

let formatMe = NumberFormatter()
formatMe.maximumFractionDigits = 2
formatMe.roundingMode = .up

formatMe.numberStyle = .spellOut
stringHere = "This is a string = " + formatMe.string(from: aDecimal)!

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

December 21st, 2016 by admin

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:

@IBOutlet var myWindow: NSView!

Assuming you named your window IBOutlet myWindow, you’ll be able to access the frame.width and frame.height properties like this:

myWindow.frame.height
myWindow.frame.width

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.

print ("Window height = \(myWindow.frame.height)")
print ("Window width = \(myWindow.frame.width)")

Posted in Algorithms, User Interface

December 18th, 2016 by admin

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:

        let myScreen = NSScreen.main()
        let resolution = myScreen?.frame
        let height = resolution?.size.height
        let width = resolution?.size.width
        print ("The monitor resolution is height = \(height!) and width = \(width!)")

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

December 16th, 2016 by admin

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:

import Cocoa

var testNumber : Double

testNumber = round(36.98)
testNumber = round(-36.98)
testNumber = round(36.08)

testNumber = floor(36.98)
testNumber = floor(-36.98)
testNumber = floor(36.08)

testNumber = ceil(36.98)
testNumber = ceil(-36.98)
testNumber = ceil(36.08)

testNumber = trunc(36.98)
testNumber = trunc(-36.98)
testNumber = trunc(36.08)

However, if you want to round decimal numbers to a fixed number of decimal places, you may find the following function handy:

func roundToPlaces(value: Double, decimalPlaces: Int) -> Double {
    let divisor = pow(10.0, Double(decimalPlaces))
    return round(value * divisor) / divisor
}

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:

import Cocoa

var number = 23.45
var number2 = 1.29
var total : Double

func roundToPlaces(value: Double, decimalPlaces: Int) -> Double {
    let divisor = pow(10.0, Double(decimalPlaces))
    return round(value * divisor) / divisor
}


total = roundToPlaces(value: number / number2, decimalPlaces: 3)

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

December 12th, 2016 by admin

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:

let colorPanel = NSColorWell()

Next, you need to actually display that color panel using the activate command:

colorPanel.activate(true)

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:

colorPanel.action = #selector(changeColor(_:))

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:

    override func changeColor(_ sender: Any?) {
        myLabel.textColor = colorPanel.color
    }

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:

import Cocoa

class ViewController: NSViewController {

    @IBOutlet weak var myLabel: NSTextField!
    
    let colorPanel = NSColorWell()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    override func changeColor(_ sender: Any?) {
        myLabel.textColor = colorPanel.color
    }
    
    @IBAction func chooseColor(_ sender: NSButton) {
        colorPanel.activate(true)
        colorPanel.action = #selector(changeColor(_:))
    }

}

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

HTML Snippets Powered By : XYZScripts.com