Setting backgroundColor of custom NSView - swift

What is the process of drawing to NSView using storyboards for osx? I have added a NSView to the NSViewController. Then, I added a few constraints and an outlet.
Next, I added some code to change the color:
import Cocoa
class ViewController: NSViewController {
#IBOutlet var box: NSView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear() {
box.layer?.backgroundColor = NSColor.blueColor().CGColor
//box.layer?.setNeedsDisplay()
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
}
I would like to do custom drawing and changing colors of the NSView. I have
performed sophisticated drawing on iOS in the past, but am totally stuck here.
Does anyone see what I'm doing wrong?

The correct way is
class ViewController: NSViewController {
#IBOutlet var box: NSView!
override func viewDidLoad() {
super.viewDidLoad()
self.view.wantsLayer = true
}
override func viewWillAppear() {
box.layer?.backgroundColor = NSColor.blue.cgColor
//box.layer?.setNeedsDisplay()
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}}

Swift via property
extension NSView {
var backgroundColor: NSColor? {
get {
if let colorRef = self.layer?.backgroundColor {
return NSColor(CGColor: colorRef)
} else {
return nil
}
}
set {
self.wantsLayer = true
self.layer?.backgroundColor = newValue?.CGColor
}
}
}
Usage:
yourView.backgroundColor = NSColor.greenColor()
Where yourView is NSView or any of its subclasses
Updated for Swift 3
extension NSView {
var backgroundColor: NSColor? {
get {
if let colorRef = self.layer?.backgroundColor {
return NSColor(cgColor: colorRef)
} else {
return nil
}
}
set {
self.wantsLayer = true
self.layer?.backgroundColor = newValue?.cgColor
}
}
}

edit/update:
Another option is to design your own colored view:
import Cocoa
#IBDesignable class ColoredView: NSView {
#IBInspectable var backgroundColor: NSColor = .clear
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
backgroundColor.set()
dirtyRect.fill()
}
}
Then you just need to add a Custom View NSView and set the custom class in the inspector:
Original Answer
Swift 3.0 or later
extension NSView {
var backgroundColor: NSColor? {
get {
guard let color = layer?.backgroundColor else { return nil }
return NSColor(cgColor: color)
}
set {
wantsLayer = true
layer?.backgroundColor = newValue?.cgColor
}
}
}
let myView = NSView(frame: NSRect(x: 0, y: 0, width: 100, height: 100))
myView.backgroundColor = .red

This works a lot better:
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
NSColor.blueColor().setFill()
NSRectFill(dirtyRect);
}

Best way to set a NSView background colour in MacOS 10.14 with dark mode support :
1/ Create your colour in Assets.xcassets
2/ Subclass your NSView and add this :
class myView: NSView {
override func updateLayer() {
self.layer?.backgroundColor = NSColor(named: "customControlColor")?.cgColor
}
}
Very simple and dark mode supported with the colour of your choice !
Full guide : https://developer.apple.com/documentation/appkit/supporting_dark_mode_in_your_interface

Just one line of code is enough to change the background of any NSView object:
myView.setValue(NSColor.blue, forKey: "backgroundColor")
Instead of this, you can also add an user defined attribute in the interface designer of type Color with keyPath backgroundColor.

Update to Swift 3 solution by #CryingHippo (It showed colors not on every run in my case). I've added DispatchQueue.main.async and now it shows colors on every run of the app.
extension NSView {
var backgroundColor: NSColor? {
get {
if let colorRef = self.layer?.backgroundColor {
return NSColor(cgColor: colorRef)
} else {
return nil
}
}
set {
DispatchQueue.main.async {
self.wantsLayer = true
self.layer?.backgroundColor = newValue?.cgColor
}
}
}
}

None of the solutions is using pure power of Cocoa framework.
The correct solution is to use NSBox instead of NSView. It has always supported fillColor, borderColor etc.
Set titlePosition to None
Set boxType to Custom
Set borderType to None
Set your desired fillColor from asset catalogue (IMPORTANT for dark mode)
Set borderWidth and borderRadius to 0
Bonus:
it dynamically reacts to sudden change of appearance (light to dark)
it supports animations ( no need for dynamic + no need to override animation(forKey key:NSAnimatablePropertyKey) ->)
future macOS support automatically
WARNING:
Using NSBox + system colors in dark mode will apply tinting corectly. If you do not want tinting use catalogue color.
Alternative is to provide subclass of NSView and do the drawing updates in updateLayer
import Cocoa
#IBDesignable
class CustomView: NSView {
#IBInspectable var backgroundColor : NSColor? {
didSet { needsDisplay = true }
}
override var wantsUpdateLayer: Bool {
return true
}
override func updateLayer() {
guard let layer = layer else { return }
layer.backgroundColor = backgroundColor?.cgColor
}
}
Tinting:

Since macOS 10.13 (High Sierra) NSView responds to selector backgroundColor although it is not documented!

Related

In the main.storyboard the rounded button aren't load

I have add the class RoundButton in Swift with the following code:
//
// RoundButton.swift
//
import UIKit
#IBDesignable
class RoundButton: UIButton {
#IBInspectable var roundButton : Bool = false {
didSet {
if roundButton == true {
layer.cornerRadius = frame.height / 2
}
}
}
override func prepareForInterfaceBuilder() {
if roundButton == true {
layer.cornerRadius = frame.height / 2
}
}
}
Then I have activate the design in the button properties. In the main.storyboard the buttons are square, but in the build the buttons are round. And it comes this error:
file:///Users/anonymoushuman/Documents/Apps/Taschenrechner/Taschenrechner/Base.lproj/Main.storyboard: error: IB Designables: Failed to render and update auto layout status for ViewController (BYZ-38-t0r): The bundle “Taschenrechner.app” couldn’t be loaded because its executable couldn’t be located.
Your code works normally.
I also have the same version [Xcode 12.5.1].
I searched for the errors you experienced, and I think it would be good to refer to the links.
https://developer.apple.com/forums/thread/665826
I don't know what caused the error, but let me suggest another way.
This code can also achieve the same results you want to achieve.
import UIKit
extension UIButton {
func makeCircle() {
self.layer.masksToBounds = true
self.layer.cornerRadius = self.frame.width / 2
}
}
result
This is the extension I wrote. If you want to make a circle, not an ellipse, you can write button.makeRounded(nil). The caution here is that when you make a circle, the vertical and horizontal heights must be equal and the values must be specified.
extension UIButton {
func makeRounded(cornerRadius : CGFloat?) {
if let cornerRadius_ = cornerRadius {
self.layer.cornerRadius = cornerRadius_
} else {
self.layer.cornerRadius = self.layer.frame.height / 2
}
self.layer.masksToBounds = true
}

Programmatically emptying UIStackView

I have a fairly simple code which, upon clicking a button, adds a randomly colored UIView to a UIStackView, and upon a different button click, removes a random UIView from the UIStackView.
Here's the code:
import UIKit
class ViewController: UIViewController, Storyboarded {
weak var coordinator: MainCoordinator?
#IBOutlet weak var stackView: UIStackView!
var tags: [Int] = []
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func buttonPressed(_ sender: UIButton) {
switch sender.tag {
case 10:
let view = UIView(frame: CGRect(x: 0, y: 0, width: stackView.frame.width, height: 20))
var number = Int.random(in: 0...10000)
while tags.contains(number) {
number = Int.random(in: 0...10000)
}
tags.append(number)
view.tag = number
view.backgroundColor = .random()
stackView.addArrangedSubview(view)
case 20:
if tags.count == 0 {
print("Empty")
return
}
let index = Int.random(in: 0...tags.count - 1)
let tag = tags[index]
tags.remove(at: index)
if let view = stackView.arrangedSubviews.first(where: { $0.tag == tag }) {
stackView.removeArrangedSubview(view)
}
default:
break
}
}
}
extension CGFloat {
static func random() -> CGFloat {
return CGFloat(arc4random()) / CGFloat(UInt32.max)
}
}
extension UIColor {
static func random() -> UIColor {
return UIColor(
red: .random(),
green: .random(),
blue: .random(),
alpha: 1.0
)
}
}
I'm not using removeFromSuperview on purpose - since I would (later) want to reuse those removed UIViews, and that is why I'm using removeArrangedSubview.
The issue I'm facing is:
All UIViews are removed as expected (visually of course, I know they're still in the memory) until I reach the last one - which, even though was removed, still appears and filling the entire UIStackView.
What am I missing here?
You can understand removeArrangedSubview is for removing constraints that were assigned to the subview. Subviews are still in memory and also still inside the parent view.
To achieve your purpose, you can define an array as your view controller's property, to hold those subviews, then use removeFromSuperview.
Or use .isHidden property on any subview you need to keep it in memory rather than removing its contraints. You will see the stackview do magical things to all of its subviews.
let subview = UIView()
stackView.addArrangedSubview(subview)
func didTapButton(sender: UIButton) {
subview.isHidden.toggle()
}
Last, addArrangedSubview will do two things: add the view to superview if it's not in superview's hierachy and add contraints for it.

Swift not managing to call draw(GRect) more than once

I am trying to learn swift bu it seems I am already stuck.
Can someone point out why the { didSet { setNeedsDisplay() } } does not seem to work?!
The goal is to draw a small circle where the user taps
Here is my Controller:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var display: UIView!{
didSet{
display.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(addCirclePoint(byReactingTo:))))
}
}
let pointsAndLines = PointsAndLinesView()
func addCirclePoint(byReactingTo tapRecognizer: UITapGestureRecognizer){
let point = tapRecognizer.location(in: display)
pointsAndLines.point = point
}
}
And here is my View:
import UIKit
class PointsAndLinesView: UIView {
var point = CGPoint(){ didSet{ setNeedsDisplay() } }
private func addCirclePoint()->UIBezierPath{
let circlePoint = UIBezierPath(arcCenter: point, radius: 5.0, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: true)
circlePoint.lineWidth = 4
print("Did I run?!")
return circlePoint
}
override func draw(_ rect: CGRect) {
UIColor.black.set()
addCirclePoint().stroke()
}
}
Looking forward to your responses.
EDIT:
For future reference in case someone needs it the mistake was,
that display is a subclass of PointsAndLinesView and NOT of UIView
and display.point should be set.
Looking at the code you have never added the pointsAndLines control to a view so you will never see it. You can add it as a subview of the main view and then set it's frame manually or use auto layout to position it.

Using a CALayer in an NSStatusBarButton

I'm interested in drawing custom content in a NSStatusBarButton similar to the built-in battery menu bar app:
I'd like to use a CALayer due to the flexibility of drawing custom content. I've managed to add a layer-backed NSView to the button using this code:
// StatusView
class StatusView: NSView {
required init?(coder: NSCoder) {
super.init(coder: coder)
self.wantsLayer = true
}
override var wantsUpdateLayer: Bool {
return true
}
override func updateLayer() {
if let layer = self.layer {
layer.backgroundColor = NSColor.clear.cgColor
// Code adding text layer...
}
}
}
// MenuController
class StatusMenuController: NSObject {
override func awakeFromNib() {
if let button = statusItem.button {
layerView.frame = NSRect(x: 0.0, y: 0.0, width: len / 2, height: button.bounds.height)
button.addSubview(layerView)
}
}
}
Basically I'm adding a CALayer to the button of the NSStatusBarButton, which looks fine normally, but seems to have an opaque background when you click the menu item:
I've set the background color of the CALayer to transparent and the isOpaque property of the layer's view is false. Is there a way to get the view to actually blend with the background, similar to the battery menu bar app?
Thanks!

Swift set UIButton setBorderColor in Storyboard

I'm trying to set UIButton Border color on Storyboard:
But the button is still Black. When I try to use layer.borderColor, it doesn't show the border at all.
How to se the color?
Thank you
// UPDATE
I've changed the way to set up based on #dfd to:
import Foundation
import UIKit
#IBDesignable
public class OnboardingButton: UIButton {
#IBInspectable public var borderColor:UIColor? {
didSet {
layer.borderColor = borderColor?.cgColor
}
}
#IBInspectable public var borderWidth:CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
#IBInspectable public var cornerRadius:CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
}
After set up in Storyboard Custom Class to *OnboardingButton app started build but Faield. There is no error in the Log. Where can I find the error and how to fix it?
Here's my UIButton subclass:
#IBDesignable
public class Button: UIButton {
#IBInspectable public var borderColor:UIColor? {
didSet {
layer.borderColor = borderColor?.cgColor
}
}
#IBInspectable public var borderWidth:CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
#IBInspectable public var cornerRadius:CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
}
EDIT:
I created a simple project and added the above IBDesignable subclass. Below are three screen shots of the result. Note that in the Identity inspector I've set the Class to be Button, not UIButton and that it reports that the Designables are "Up to date". Note that in the Attributes inspector these appear as properties at the very top.
You can change some properties of UIButton form interface builder but not color of border. Another way would be subclassing it like in answer suggested by dfd.