Reputation: 39
I'm having an issue where when my asset catalog have more than 2 images (all have @1x @2x and @3x), my NSImage in my NSImageView cannot be clicked. Does anyone know why this happens?
Thanks in advance!
import SwiftUI
struct ContentView: View {
@State private var window: NSWindow?
var body: some View {
VStack {
Button("Open Window") {
// Create and show the NSWindow
self.window = NSWindow(
contentRect: NSScreen.main?.frame ?? NSRect.zero,
styleMask: [.borderless],
backing: .buffered,
defer: false
)
// Set up window properties
self.window?.isOpaque = false
self.window?.hasShadow = false
self.window?.backgroundColor = .clear
self.window?.level = .screenSaver
self.window?.collectionBehavior = [.canJoinAllSpaces]
self.window?.makeKeyAndOrderFront(nil)
// Create an NSImageView
let petView = PetView()
// Add the NSImageView to the window's content view
if let contentView = self.window?.contentView {
contentView.addSubview(petView)
// Center the petView
petView.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
petView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
}
}
}
}
}
class PetView: NSImageView {
override init(frame frameRect: NSRect = .zero) {
super.init(frame: frameRect)
self.image = NSImage(named: "dog_idle-1")
self.translatesAutoresizingMaskIntoConstraints = false
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func mouseDown(with event: NSEvent) {
print("woof!")
}
}
I've tried changing the amount of images in my asset catalog and found that 2 is the maximum amount for my code to work. It suppose to print "woof!" when i click on it.
Upvotes: 0
Views: 41
Reputation: 39
Apparently, if i put all my assets directly in my bundle instead of the asset catalog everything works fine. So i guess that is the simplest solution for now...
class PetView: NSImageView {
override init(frame frameRect: NSRect = .zero) {
super.init(frame: frameRect)
let imageName = "dog_idle-1"
// Find image path for image
let imagePath = Bundle.main.path(forResource: imageName, ofType: "png")!
// Load image from image path
let image = NSImage(contentsOfFile: imagePath)
self.image = image
self.translatesAutoresizingMaskIntoConstraints = false
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func mouseDown(with event: NSEvent) {
print("woof!")
}
}
Upvotes: 0