Category: macOS

February 24th, 2017 by admin

A Split View Controller can display two or more views side by side. Separating the views is a divider that the user can drag back and forth to widen shrink a view. There are two ways to change the appearance of this divider:

  • Choose a style
  • Choose a color

The divider style can appear as Thick, Thin, or Pane Splitter. Strangely, the Thick and Pane Splitter styles look nearly identical with the only difference being that you can change the color of a Thick divider but not a Pane Splitter divider.

To choose a divider style, open the Document Outline pane and click on the Split View.

Next, open the Attributes Inspector pane by choosing View > Utilities > Show Attributes Inspector. In the Style popup menu, choose the style you want for your divider.

Changing the color of the divider is a bit stranger and trickier. Open the Document Outline pane and click on Split View. Now open the Identity Inspector pane by choosing View > Utilities > Show Identity Inspector.

Look for the User Defined Runtime Attributes category and click on the + icon. This creates a generic row of data listing keyPath, Boolean, and a check mark.

Double-click on keyPath and change this text to dividerColor and press Return.

Under the Type column, click the popup menu and change Boolean to Color.

Under the Value category, click the popup menu that appears there and choose a color.

If you chose a Thick or Thin style (not a Pane Splitter) and defined a color, run your project and you should see your chosen divider style and color appear in the split view.

 

 

Posted in 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 28th, 2017 by admin

When you create a macOS Cocoa Application project, you project starts out with a Window Controller and a View Controller.

The Window Controller defines the actual window that appears on the screen but the View Controller defines the contents that appears inside the Window Controller. You need to place user interface items like buttons and text fields on the View Controller so when your program runs, these user interface items appear on the View Controller, which appears inside the Window Controller.

A View Controller represents a simple window, but Xcode offers several other types of view controllers such as a Page Controller, a Split View Controller, and a Tab View Controller. If you want any of these other types of controllers to appear inside the Window Controller, you need to follow two steps:

  • Delete the currently existing View Controller
  • Add the new controller you want to put in its place such as a Tab View Controller or Page Controller

To delete the existing View Controller, you need to delete both the View Controller in the storyboard and the ViewController.swift file. To delete the ViewController.swift file in the Navigator pane, just right-click over it and when a popup menu appears, choose Delete.

To delete the View Controller from the storyboard, select the View Controller by clicking the Show Document Outline icon and then clicking on View Controller Scene in the Document Outline. Then press Backspace or choose Edit > Delete.

Initially the contents of the Window Controller displayed View Controller but now it should display No Content View Controller.

Now drag another controller from the Object Library window to the storyboard such as Page Controller or Vertical Split Controller. This will place a new controller on the storyboard but now you’ll need to connect this newly added controller to appear inside the Window Controller.

Click on the blue icon that appears in the top, middle of the Window Controller. Hold down the Control key and Control-drag over the new controller you just added.

Release the Control key and the left mouse/trackpad button. A popup menu appears.

Choose window content. Your newly added controller now displays a connecting arrow to show that it appears inside the existing Window Controller.

Posted in macOS, User Interface, Xcode

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 14th, 2017 by admin

A menu bar app is a macOS program that does not display its icon on the Dock when running or show its pull-down menus in the upper left corner of the screen. Instead, a menu bar app displays a title or icon in the upper right corner of the screen so it’s available when you need it. A typical menu bar app is the volume control icon that lets you adjust the volume or the Time Machine icon that lets you access Time Machine.

To create a menu bar app, follow the instructions in this earlier blog post. This post shows how to create a menu bar that displays a text title on the menu bar. In this post, you’ll learn how to use an icon instead.

First, you need to create an icon that’s 32 by 32 pixels in size. As an alternative to creating your own icon, you can visit Flaticon, a site that offers royalty-free icons. You can either purchase a subscription to this site or if you want to use an icon for free, you must give credit to the creator of the icon.

Icons should be stored in the .png file format. Whether you create an icon or download one from a site like Flaticon, the first step is to drag it into the Assets.xcassets folder of your Xcode project.

Click on your icon file name and choose View > Utilities > Show Attributes Inspector.

Make sure the “Mac” check box is selected and all other check boxes are clear.

Change the Render As popup menu to Template image.

Make sure your graphic image appears in the 2x box.

Remember the exact name of your icon file such as “egyptian-cat” without the .png file extension.

If you followed the first part about creating a menu bar app, you used code like this:

item?.title = "TestMe"

This code creates a text title on the menu bar. Delete this line and replace it with the following:

item?.image = NSImage(named: "egyptian-cat")

In the above example, “egyptian-cat” is the name of the icon file stored in the Assets.xcassets folder so replace this name with the actual name of your own icon file.

Now your icon will appear on the menu bar.

 

Posted in macOS, Xcode

January 10th, 2017 by admin

If you look in the upper right corner on the menu bar of any Macintosh, you’ll see plenty of icons that represent volume control or access to your Time Machine backups. If you want to create a little utility that can be accessed through the menu bar, you need to create a menu bar app.

Unlike a regular macOS program, a menu bar app does not display a list of pull-down menu items, nor does a menu bar app display an icon on the Dock when it’s running. All a menu bar app needs to do is display an icon or menu title on the menu bar along with a menu of options for the user to choose from.

The first step to creating a menu bar app is to create a new macOS project Cocoa Application project where the “Use Storyboards” checkbox is clear. This will create a project that contains pull-down menus and a single window represented by a .xib file.

First, you can delete the .xib file or hide it. To hide the .xib window, click on it and choose View > Utilities > Show Attributes Inspector. Now clear the “Visible At Launch” check box. This keeps the window from appearing but still keeps it in your project in case you need it for any reason.

Once you’ve deleted or hidden the .xib window, the next step is to make sure the pull-down menus and program icon don’t appear on the Dock. To do this, click the Info.plist file in the Navigator pane to display a long list of various options.

Click on the last option and a + and – sign icon appears. Click this + icon to create a new line. In this new line, choose “Application is agent (UIElement)”.

Make sure the Type for this line is Boolean and its Value is YES. This option will keep the program’s icon from appearing on the Dock when running and keep its pull-down menus from appearing on the left side of the menu bar at the top of the screen.

Once you’ve hidden the window, pull-down menus, and Dock icon, the last step is to write Swift code to create the menu bar title and a pull-down menu.

Open the AppDelegate.swift file and underneath the class AppDelegate line, add the following:

var item : NSStatusItem? = nil

This creates the object that will appear on the status bar. Inside the applicationDidFinishLaunching function, you need to assign this “item” object an actual value:

item = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)

The above code creates an object, but we still need to display it on the menu bar. One way to display the menu bar is as an icon (which will be covered in a future blog post). A second way is as text, which you can create by defining its title property like this:

item?.title = "MyMenu"

The string assigned to the title property can be anything you want, but keep it short and descriptive.

After you’ve created a menu title, the next step is to create a pull-down menu list. To do this, you need to create an NSMenu object and then fill it with titles like this:

let menu = NSMenu()
menu.addItem(NSMenuItem(title: "Option 1", action: #selector(AppDelegate.testMe), keyEquivalent: ""))
menu.addItem(NSMenuItem(title: "Quit", action: #selector(AppDelegate.quitMe), keyEquivalent: ""))
item?.menu = menu

To define each item in the pull-down menu, you need to use the addItem command. The title property defines the command that appears on the menu and the #selector identifies the function that runs when the user clicks on that menu item.

The keyEquivalent property lets you define a letter that represents a shortcut keystroke for accessing the command. In general, it’s best to leave it blank because it takes more time to use the keystroke shortcut than it will to simply click on the menu item they want.

Finally, you need to assign your NSMenu object to your menu bar’s menu property.

At this point, your pull-down menus will appear but won’t do anything because you still need to write functions that run when the user clicks on a particular menu item.

In the above example, the two #selector commands are looking for a testMe and a quitMe function (although you can choose any name you wish). So if you used the above code, the two functions you’d need to create are as follows:

    func testMe() {
        print ("It works!")
    }
    
    func quitMe() {
        NSApplication.shared().terminate(self)
    }

The NSApplication.shared().terminate(self) command simply quits the program.

The complete code of the AppDelegate.swift file should look like this:

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!

    var item : NSStatusItem? = nil
    
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        
        item = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
        
        //Displays text on menu bar
        item?.title = "TestMe"
        
        // Defines function to run when the user clicks on the text on menu bar
        //item?.action = #selector(AppDelegate.testMe)
        
        let menu = NSMenu()
        menu.addItem(NSMenuItem(title: "Option 1", action: #selector(AppDelegate.testMe), keyEquivalent: ""))
        menu.addItem(NSMenuItem(title: "Quit", action: #selector(AppDelegate.quitMe), keyEquivalent: ""))
        item?.menu = menu
    }
    
    func testMe() {
        print ("It works!")
    }
    
    func quitMe() {
        NSApplication.shared().terminate(self)
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }


}

If you choose Product > Run, you should see the menu text “TestMe” appear on the menu bar. If you click on it, a pull-down menu appears displaying “Option 1” and “Quit”. If you click Option 1, the program prints “It works!” in the Debug area of the Xcode window. If you click Quit, your program stops running.

This simple project demonstrates how to create a simple menu bar app that displays a menu title (“TestMe”) on the menu bar. When the user clicks on this menu title, a pull-down menu appears with two options.

You can download the complete MenuBarApp project here.

Posted in macOS, Programming, Xcode

January 7th, 2017 by admin

At one time, the only way to create user interfaces for macOS or iOS programs was to use .xib files. Nowadays, the only way to create user interfaces for iOS apps is to use storyboard files. To create macOS programs, you still have the option of using either .xib or .storyboard files, but since storyboards are used for iOS programming, you might as well start using storyboards for creating macOS user interfaces as well.

When you use storyboards to create a macOS project, you can create segues between scenes (windows) in your storyboard. For example, create a macOS Cocoa Application project that uses storyboards and you’ll wind up with a single window controller that looks like this:

The top box is the window controller and the bottom box is the view controller that appears inside the window controller. (Yes, I know this sounds confusing because it is.)

You need to add user interface items like buttons and text fields in the bottom box (the view controller). That view controller box is also connected to a class file called ViewController.swift so you can write IBOutlets and IBAction methods to control any user interface items you add to the view controller box.

If you want to add another scene to a storyboard, you have to drag a view controller from the Object Library on to the storyboard. Xcode offers several different types of view controllers such as the plain View Controller or the more sophisticated Tab View Controller or Horizontal/Vertical Split View Controller, which offers more than just a single window to display on the screen. Xcode offers the following types of view controllers you can add to a storyboard.

Whatever type of new controller you want to add to a storyboard doesn’t matter but whatever type you add, you must create a Swift Cocoa Class file to control that view controller. So if you add a View Controller, you must create a Cocoa Class file that’s a subclass of NSViewController. If you add a Page Controller, you must create a Cocoa Class file that’s a subclass of NSPageController.

After you’ve added a view controller to a storyboard, you need to choose File > New > File to create a macOS Cocoa Class as shown below.

After clicking the Next button in the bottom right corner, you need to give your class file a name (which can be anything, but more importantly, you must choose a subclass as shown below.

Once you’ve chosen the proper subclass to represent your newly added view controller in the storyboard, the final step is to connect that class file to the view controller in the storyboard.

To do this, click on your storyboard file in the Navigator pane and then click on the blue icon at the top, middle of the newly added view controller to select it. Choose View > Utilities > Show Identity Inspector. In the Class popup menu, choose the name of the class file you just created.

It’s important to remember that every view controller (scene) in a storyboard needs to be connected to a class file. When you add various user interface items to a view controller (scene), you can open the Assistant Editor and control-drag to create IBOutlets and IBAction methods in the class file connected to that view controller.

Posted in macOS, User Interface, Xcode

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 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