Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Macos NSView有背景色吗?如果有,我可以';我找不到_Macos_Cocoa_Nsview_Background Color - Fatal编程技术网

Macos NSView有背景色吗?如果有,我可以';我找不到

Macos NSView有背景色吗?如果有,我可以';我找不到,macos,cocoa,nsview,background-color,Macos,Cocoa,Nsview,Background Color,我看到网上到处都有人提到NSView的背景色。我需要为我的NSView设置自定义背景色,但我没有看到该属性。我无法在代码或IB中看到它。我无法设置简单NSView的背景色 我可能遗漏了什么?他们一定在想UIView,它确实有backgroundColor属性NSView不具有backgroundColor属性 您必须以其他方式实现效果,例如,通过子类化NSView您可以通过视图的层来实现效果,例如(在Swift中): 奇怪的是,它可以设置在xib中。在视图的标识检查器中,添加用户定义的运行时属性

我看到网上到处都有人提到NSView的背景色。我需要为我的NSView设置自定义背景色,但我没有看到该属性。我无法在代码或IB中看到它。我无法设置简单NSView的背景色


我可能遗漏了什么?

他们一定在想
UIView
,它确实有
backgroundColor
属性
NSView
不具有
backgroundColor
属性


您必须以其他方式实现效果,例如,通过子类化
NSView

您可以通过视图的层来实现效果,例如(在Swift中):


奇怪的是,它可以设置在xib中。在视图的标识检查器中,添加用户定义的运行时属性
backgroundColor
,类型为color。

奇怪的是,NSView没有提供此功能(叹气)。在我所有的macOs项目中,我都使用我自己编写的一个一致的类。只需将IB中Identity Inspector选项卡中的CustomView类更改为ColorView。然后,您可以在属性检查器中设置背景色,就像在UIView中一样。这是代码,希望这有帮助

import Cocoa

class ColorView: NSView
{
    @IBInspectable var backgroundColor:NSColor?

    required init?(coder decoder: NSCoder)
    {
        super.init(coder: decoder)
        wantsLayer = true
    }

    override init(frame frameRect: NSRect)
    {
        super.init(frame: frameRect)
        wantsLayer = true
    }

    override func layout()
    {
        layer?.backgroundColor = backgroundColor?.cgColor
    }
}

这真的很奇怪,他们没有现成的方法来更改视图的背景色。谢谢你的邀请answer@Wes:这是因为
NSView
本身并不能真正起到任何作用。它没有画任何东西。我很难想象这样一种情况:需要设置背景色,但还没有对视图进行子类化。
import Cocoa

class ColorView: NSView
{
    @IBInspectable var backgroundColor:NSColor?

    required init?(coder decoder: NSCoder)
    {
        super.init(coder: decoder)
        wantsLayer = true
    }

    override init(frame frameRect: NSRect)
    {
        super.init(frame: frameRect)
        wantsLayer = true
    }

    override func layout()
    {
        layer?.backgroundColor = backgroundColor?.cgColor
    }
}