Playing with the Borders of a View

When you create a macOS project that uses storyboards, each window is called a view, which has a border. Two ways to modify the border of a view is to change its width and change its color.

To change the view’s border width, you need to use the borderWidth property like this:

self.view.layer?.borderWidth = 5

One way to make it easy to change the width of a border is to use a slider. Then create an IBOutlet for that slider along with an IBAction method like this:

@IBOutlet weak var borderSlider: NSSlider!

@IBAction func sliderChanged(_ sender: NSSlider) {
        self.view.layer?.borderWidth = CGFloat(borderSlider.intValue)
}

To change the view’s border color, you need to use the borderColor property like this:

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

The simplest way to change the border color is through a color well. Just create an IBOutlet and an IBAction method for that color well, in addition to overriding the changeColor function like this:

@IBOutlet weak var colorWell: NSColorWell!

@IBAction func pickColor(_ sender: NSColorWell) {
        colorWell.activate(true)
        colorWell.action = #selector(changeColor)
}
    
override func changeColor(_ sender: Any?) {
        self.view.layer?.borderColor = colorWell.color.cgColor
}

If you have a slider and a color well on your view, users can drag the slider back and forth to modify the border width and click on the color well to choose a different color for that border. You can download a sample program that shows how this works:

BorderSetting sample program.

May 4th, 2017 by
HTML Snippets Powered By : XYZScripts.com