objective-c - 使用 NSBox 在 NSCollectionView 中突出显示所选项目

标签 objective-c xcode cocoa nscollectionview

如何更新 NSCollectionView 以使用 NSBox 显示当前选定的项目?在列表中显示选择似乎是一件基本的事情,但我在这方面遇到了各种各样的麻烦。

我读过这篇文章question还查看了 sample code来自苹果。似乎有几种方法可以做到这一点。

  1. 使用 NSCollectionViewItem 的子类和特殊的“原型(prototype) View ”。
  2. 使用NSBox

我希望使用NSBox方式,因为它看起来很简单,并且也在官方代码示例中使用。

这显然是按照 alternegro 的以下引用所述完成的。 :

If a different background color will suffice as a highlight, you could simply use an NSBox as the root item for you collection item view. Fill the NSBox with the highlight color of your choice. Set the NSBox to Custom so the fill will work. Set the NSBox to transparent.

Bind the transparency attribute of the NSBox to the selected attribute of File Owner(Collection Item) Set the value transformer for the transparent binding to NSNegateBoolean.

我被困在第一部分:“使用 NSBox 作为你(原文如此)集合项 View 的根项”。我尝试将“自定义类”更改为继承自 NSBoxFoobarBox,但它似乎没有帮助,因为我无法将背景颜色更改为蓝色,也不能我绑定(bind)透明度。任何关于如何在我的 NSCollectionVuew 中显示选择的指示将不胜感激。

最佳答案

首先,为 ListView 创建一个继承自 NSBox 的类

 @interface MyListViewBox : NSBox

    @property (unsafe_unretained) IBOutlet NSCollectionViewItem *controller;

 @end

然后,在 Interface Builder 中,将类名称指定为“自定义类”属性,如我的屏幕截图所示

screenshot

然后您将意识到 IB 不会在 GUI 中显示 NSBox 属性或绑定(bind)(至少在版本 4.5.2 中),因此我决定以编程方式更改属性。

  • 在 NSBox 子类中为 NSCollectionViewItem 创建一个 socket (如上所示)
  • 使用 IB 将 socket 链接到您的 NSCollectionItemView

  • 在 NSBox 子类的 -(void)awakeFromNib 中,添加以下代码

    -(void)awakeFromNib { 
    
      //properties are not showing up in XCode Inspector IB view
      //configuring the box here :-(
    
      self.boxType = NSBoxCustom;
      self.borderType = NSLineBorder;
      self.fillColor = [NSColor selectedControlColor];
    
      //bind the "transparent" property of NSBox to the "selected" property of NSCollectionViewItem controller
      //controller is bound as IBOutlet in IB
      NSValueTransformer* transformer = [NSValueTransformer valueTransformerForName:NSNegateBooleanTransformerName];
      [self bind:@"transparent"
        toObject:self.controller 
        withKeyPath:@"selected"
        options:[NSDictionary dictionaryWithObjectsAndKeys:transformer, NSValueTransformerBindingOption, nil]];
    }
    

关于objective-c - 使用 NSBox 在 NSCollectionView 中突出显示所选项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9066701/

相关文章:

objective-c - nil 和 nil 有什么区别

iphone - 错误的委托(delegate)声明

ios - Xcode 4.4 - 无法运行项目

iOS facebook 获取通知

objective-c - 最简单的 Cocoa Binding 示例

iOS 无损图像编辑

objective-c - 检查 NSString 是否只是由空格组成

objective-c - 如何在 Xcode 中自动完成 block 签名?

iphone - 使图像适合 UINavigationBar 栏

objective-c - 当我尝试创建 NSSpeechSynthesizer 实例时获取 EXC_BAD_ACCESS