【问题标题】:Set background color of NSView and NSImageView in cocoa在 cocoa 中设置 NSView 和 NSImageView 的背景颜色
【发布时间】:2014-07-29 21:04:41
【问题描述】:

我有一些我在 IB 中制作的 NSViews % NSImageView,当应用程序 awakesFromNib 时,如何为每个设置背景颜色?

在 google 和在这里搜索之后,我发现可以通过创建 NSView 或 NSImageView 的自定义类并在它们的 drawRect 方法中设置颜色来完成。

他们是否可以通过其他方式设置背景颜色,并且无需为 View/ImageView 创建额外的类。

谢谢

【问题讨论】:

  • AFAIK 没有其他办法。您需要子类化视图来设置背景颜色。

标签: objective-c cocoa background-color


【解决方案1】:

他们是设置NSView/NSImageView背景颜色的两种方式,我找到了。

第一:通过NSView/NSImageView的子类化

- (void)drawRect:(NSRect)aRect
{
    [[NSColor redColor] set];
    NSRectFill([self bounds]);
}

第二:

不想创建子类,正如您在问题中提到的那样。 那么

[_backgroundView setWantsLayer:YES];
[_backgroundView.layer setBackgroundColor:[[NSColor redColor] CGColor]]];

这里的_backgroundViewNSView/NSImageView 的IBOutlet/对象。您只需要访问NSView/NSImageView 层即可为他提供背景色,而无需对其进行子类化。

【讨论】:

  • 可以在没有 CGColor 的情况下完成“第二个”(或类似的东西)吗? F.e.在没有 CGColor 可用的系统版本上?
  • @silverdr 您在哪个版本上工作?你也在使用 Objective-C 或 Swift 吗?
  • 我使用 Obj-C 的目标是 10.6+(苹果妈妈现在允许的最低值)。
【解决方案2】:

如果没有子类化 NSView,你不能绘制自定义的东西,但是你可以改变图层的背景颜色。

[yourView setWantsLayer: YES];
[yourView.layer setBackgroundColor: [NSColor redColor].CGColor];

【讨论】:

    【解决方案3】:

    您可以通过 Interface Builder 为任何 NSView 后代应用背景颜色,方法是实现如下类别扩展:

    @implementation NSView (backgroundColor)
    
    - (void)setBgColor:(NSColor *)color {
        //
        [self setWantsLayer:YES];
        self.layer = [CALayer layer];
        [self.layer setBackgroundColor:[color CGColor]];
    }
    
    @end
    

    并在 IB 的 User Defined Runtime Attributes 面板中为其提供一个值:

    【讨论】:

      【解决方案4】:

      在 Swift 中,您可以像这样更改 NSImageView 背景颜色:

      self.myBackgroundView.wantsLayer = true
      self.myBackgroundView.layer?.backgroundColor = NSColor.red.cgColor
      

      如果您想要一张图片作为背景,您可以使用以下内容:

      self.myBackgroundView.wantsLayer = true
      let image : NSImage = #imageLiteral(resourceName: "imageResourceName")
      self.myBackgroundView.layer?.backgroundColor = NSColor.init(patternImage: image).cgColor
      

      【讨论】:

        猜你喜欢
        • 2011-11-24
        • 1970-01-01
        • 2011-10-15
        • 1970-01-01
        • 2013-03-06
        • 1970-01-01
        • 1970-01-01
        • 2015-11-18
        • 1970-01-01
        相关资源
        最近更新 更多