A Button is a user interface object that you click to send an action message to the target. Most of its work is handled by the NSButtonCell, and when the NSButtonCell instance is clicked, the mouse-down event is captured and the instance sends an action message to its target.

Button type

Cocoa implements many different types for NSButtons. Button types determine the behavior of buttons. There are three types of buttons:

  • Press the button
  • Sticky button
  • Radio buttons and check boxes

We can set the button type using the setButtonType: method:

lazy var button: NSButton = {
    let button = NSButton()
    button.setButtonType(.pushOnPushOff)
    return button
}()
Copy the code

Press the button

Pressing buttons is most useful for triggering actions because they do not show their state. When clicked, they change their appearance; When unclicked, the original look is restored.

We can set the Button Type to NSButtonTypeMomentaryPushIn to set to press the Button:

lazy var button: NSButton = {
    let button = NSButton(title: "button", target: self, action: #selector(click))
    button.setButtonType(.momentaryPushIn)
    button.frame = NSRect(x: 18, y: 100, width: 70, height: 25)
    return button
}()
Copy the code

To control the appearance of your button when you press it, use NSMomentaryChangeButton. When the mouse button is pressed, it displays alternate images and titles. When the mouse button is released, it displays the normal image and title. If not set, its appearance will not change:

lazy var button1: NSButton = {
    let button = NSButton()
    button.setButtonType(.momentaryChange)
    button.title = "button"
    button.alternateTitle = "Change"
  	button.bezelStyle = .regularSquare
    button.frame = NSRect(x: 18, y: 100, width: 70, height: 25)
    return button
}()
Copy the code

Sticky button

The sticky button retains its state when pressed. After one is clicked, it saves the pressed state until the next click resumes it. We can press the Button by setting the Button Type to NSPushOnPushOffButton:

lazy var onOrOffButton: NSButton = {
    let button = NSButton()
    button.setButtonType(.pushOnPushOff)
    button.title = "button"
    button.frame = NSRect(x: 210, y: 70, width: 70, height: 25)
    button.bezelStyle = .rounded
    return button
}()
Copy the code

We can use the state property to get the state of the button and determine whether the button has been selected. This sticky button is useful for showing the status of something in your application, such as whether a button in Office Word is bold or not.

To control the appearance of your sticky buttons, use the NSToggleButton. When you click one, it will display the alternate image and title. Until the next time you click Restore, it will display the normal image and title. If it is not set, its appearance does not change. Used to toggle between two states (for example, “Stop” and “start”) :

lazy var toggleButton: NSButton = {
    let button = NSButton()
    button.action = #selector(click)
    button.setButtonType(.toggle)
    button.title = "start"
    button.alternateTitle = "stop"
    button.frame = NSRect(x: 290, y: 70, width: 70, height: 25)
    button.bezelStyle = .regularSquare
    return button
}()
Copy the code

Radio buttons and check boxes

Radio buttons and check boxes, which distinguish the state of some content, are dedicated versions of NSToggleButton’s system-defined ICONS.

Button makes it look like a check box by setting type to NSButtonTypeSwitch:

The implementation code is as follows:

lazy var switchBtnView: NSView = {
    let v = NSView(frame: NSRect(x: 70, y: 90, width: 80, height: 200))
    let b1 = NSButton(title: "Red", target: self, action: #selector(click))
    b1.setButtonType(.switch)
    b1.frame = NSRect(x: 5, y: 100, width: 70, height: 25)
    v.addSubview(b1)

    let b2 = NSButton(title: "Green", target: self, action: #selector(click))
    b2.setButtonType(.switch)
    b2.frame = NSRect(x: 5, y: 130, width: 70, height: 25)
    v.addSubview(b2)

    let b3 = NSButton(title: "Blue", target: self, action: #selector(click))
    b3.setButtonType(.switch)
    b3.frame = NSRect(x: 5, y: 160, width: 70, height: 25)
    v.addSubview(b3)
    return v
}()
Copy the code

Radio buttons can select one of several options. We can achieve this effect by setting multiple Button types to NSButtonTypeSwitch and adding them to the same superview:

The implementation code is as follows:

lazy var radioBtnView: NSView = {
    let v = NSView(frame: NSRect(x: 70, y: 90, width: 80, height: 200))
    let b1 = NSButton(title: "Red", target: self, action: #selector(click))
    b1.setButtonType(.radio)
    b1.frame = NSRect(x: 5, y: 100, width: 70, height: 25)
    v.addSubview(b1)

    let b2 = NSButton(title: "Green", target: self, action: #selector(click))
    b2.setButtonType(.radio)
    b2.frame = NSRect(x: 5, y: 130, width: 70, height: 25)
    v.addSubview(b2)

    let b3 = NSButton(title: "Blue", target: self, action: #selector(click))
    b3.setButtonType(.radio)
    b3.frame = NSRect(x: 5, y: 160, width: 70, height: 25)
    v.addSubview(b3)
    return v
}()
Copy the code

Use of buttons

Handling click events

We can use the action property to set the button to handle the click event, and we can also set the target to specify the object to handle:

lazy var toggleButton: NSButton = {
    let button = NSButton()
    button.action = #selector(click)
    button.title = "start"} ()@objc private func click(_ sender: NSButton) {
    print("click button")}Copy the code

Sets the appearance of the border

We can control the border of a button by changing its shape and shadow. Control whether borders are displayed by setting isBordered. To change the shape of the border, use change button border type bezelStyle:. There are two main types of border types:

  1. Use if your buttons are primarily identified by textNSRoundedBezelStyle. It uses the appropriate border style for the text button, which is a rounded rectangle;
  2. If your button primarily identifies an icon, use itNSRegularSquareBezelStyle.NSThickSquareBezelStyleorNSThickerSquareBezelStyle.

Sets the title of the button

A button can have two headings associated with it: normal and alternate. If the button type NSMomentaryPushInButton, NSPushOnPushOffButton, NSMomentaryLightButton, or NSOnOffButton is constantly displayed only with the normal title. If the button type is NSMomentaryChangeButton or NSToggleButton, the normal title is displayed when the button state is Off (NSOffState),

If the title contains only plain text, use setTitle: or setAlternateTitle: to set the title. If you want to style of title contains text, use the setAttributedTitle: or setAttributedAlternateTitle: set the title.

To set the font for the title, use setFont: the font for the button title.

Sets the image of the button

A button can have two images associated with it: normal and alternate. If the button class is NSMomentaryPushInButton, NSPushOnPushOffButton, NSMomentaryLightButton, or NSOnOffButton, only the normal image will be displayed. If the button type is NSMomentaryChangeButton or NSToggleButton, the normal image is displayed when the button state is Off (NSOffState).

Note: If the button is a check box or radio button, do not change its image. The images of these buttons are system defined, and changing them can result in unpredictable results.

To set the position of the button image, use imagePosition with one of the following values. The default is noImage, which can be used as follows:

public enum ImagePosition : UInt {
    case noImage    // No pictures
    case imageOnly  // Only pictures
    case imageLeft  //
    case imageRight //
    case imageBelow // The following figure is above
    case imageAbove // Below
    case imageOverlaps // Bottom map, top text, overlap
    @available(OSX 10.12*),case imageLeading
    @available(OSX 10.12*),case imageTrailing
}
Copy the code

Hide button

There are two ways to hide a view by pressing a button: make it completely transparent, or show its border only when the mouse hovers over it.

  • To make the button transparent, use isTransparent. Transparent buttons track the mouse and send its actions, but do not draw themselves.

  • If the button is active or hovering above the display when its borders, please use showsBorderOnlyWhileMouseInside.

The default button

When button is set to default button. When the user presses the Return key, the default button jumps and calls its action message. To mark the button as the default, set its keyEquivalent to Return, as shown below:

button.keyEquivalent = "\r"
Copy the code

The default button has a rough outline around it, outside the border of the button. Interfaces should be designed with extra space in mind.

The equivalent key

A button can be set with an equivalent key that responds as if it was clicked when the user presses it. Note that if the key is set to equivalent to Return, this button becomes the default button.

We can use keyEquivalent to set up the equivalent bonds. For example, to set it to Return, use:

button.keyEquivalent = "\r"
Copy the code

To set the key of a button to be equivalent to a non-print character, use a defined key constant, as shown in the following example, which sets the key of a button to be equivalent to the left arrow key:

var array = [unichar(NSLeftArrowFunctionKey)]
button.keyEquivalent = NSString(characters: array, length: 1) as String
Copy the code

summary

NSButton is more powerful and complex than UIButton in iOS, and is one of the most used components in macOS development. In the next section we’ll talk about NSImageView. The full source code can be found here: github.com/dengyhgit/m… If it helps you, don’t forget to light up the little ⭐⭐. For more content, please pay attention to my official account: