xcode - 单击取消选择 NSCollectionViewItem

标签 xcode cocoa flowlayout nscollectionview nscollectionviewitem

如何通过再次单击 NSCollectionViewItem 来取消选择它?

这是我用于选择和取消选择的代码:

func collectionView(collectionView: NSCollectionView, didSelectItemsAtIndexPaths indexPaths: Set<NSIndexPath>) {
        print("selected")
        guard let indexPath = indexPaths.first else {return}
        print("selected 2")
        guard let item = collectionView.itemAtIndexPath(indexPath) else {return}
        print("selected 3")
        (item as! CollectionViewItem).setHighlight(true)
    }

    func collectionView(collectionView: NSCollectionView, didDeselectItemsAtIndexPaths indexPaths: Set<NSIndexPath>) {
        print("deselect")
        guard let indexPath = indexPaths.first else {return}
        print("deselect 2")
        guard let item = collectionView.itemAtIndexPath(indexPath) else {return}
        print("deselect 3")
        (item as! CollectionViewItem).setHighlight(false)
    }

/////////////////////

    class CollectionViewItem: NSCollectionViewItem {


        func setHighlight(selected: Bool) {

            print("high")
            view.layer?.borderWidth = selected ? 5.0 : 0.0
            view.layer?.backgroundColor = selected ? NSColor.redColor().CGColor : NSColor(calibratedRed: 204.0/255, green: 207.0/255, blue: 1, alpha: 1).CGColor
        }
    }

此代码在单击另一个项目时取消选择,但在单击同一项目时则不会。我想在单击同一项目时取消选择。

最佳答案

您可以通过观察项目的选定状态来实现此目的,并在选择项目时在项目的 View 上安装 NSClickGestureRecognizer ,并在取消选择时将其卸载。

将以下代码放在 NSCollectionViewItem 子类中的某个位置:

- (void)onClick:(NSGestureRecognizer *)sender {
    if (self.selected) {
        //here you can deselect this specific item, this just deselects all
        [self.collectionView deselectAll:nil];
    }
}

- (void)setSelected:(BOOL)selected {
    [super setSelected:selected];
    if (selected) {
        [self installGestureRecognizer];
    }
    else {
        [self uninstallGestureRecognizer];
    }
}

- (void)installGestureRecognizer {
    [self uninstallGestureRecognizer];

    self.clickGestureRecognizer = [[NSClickGestureRecognizer alloc] initWithTarget:self
                                                                            action:@selector(onClick:)];
    [self.view addGestureRecognizer:self.clickGestureRecognizer];
}

- (void)uninstallGestureRecognizer {
    [self.view removeGestureRecognizer:self.clickGestureRecognizer];
    self.clickGestureRecognizer = nil;
}

关于xcode - 单击取消选择 NSCollectionViewItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38708731/

相关文章:

xcode - 如何在 Storyboard上移动 View Controller ?

ios - 在XCode 8中使用Swift 3,如何控制UITableView subview

objective-c - Xcode4.5 汇编程序无法编译 Xcode4.4 完美处理的文件

java - 我的自定义 ViewGroup 不会在 ScrollView 内滚动

java - 无法在java中获得简单的布局

ios - 如何引用 View 中的所有 UITextfield? swift 4.2

iphone - object-c 中的 SQL "group by"算法?

swift - nsprintoperation - 检查用户选择了什么

objective-c - NSImage 不缩放

java - 使用 WrapLayout/FlowLayout 时是否可以水平对齐组件?