资产目录中的资产数量导致NSImage无法点击

问题描述 投票:0回答:1

我遇到一个问题,当我的资产目录有超过 2 个图像(全部有 @1x @2x 和 @3x)时,我的 NSImageView 中的 NSImage 无法单击。有谁知道为什么会发生这种情况?

提前致谢!

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!")
    }
}

我尝试更改资产目录中的图像数量,发现 2 是我的代码可以运行的最大数量。它应该打印“woof!”当我点击它时。

xcode swiftui nsimage nsimageview asset-catalog
1个回答
0
投票

显然,如果我将所有资产直接放入我的包中而不是资产目录中,一切都会正常工作。所以我想这是目前最简单的解决方案......

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!")
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.