Skip to content

Instantly share code, notes, and snippets.

@wojciech-kulik
Last active September 3, 2020 22:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wojciech-kulik/8b8b4ae7d8c5fa8865e128f95f23cd72 to your computer and use it in GitHub Desktop.
Save wojciech-kulik/8b8b4ae7d8c5fa8865e128f95f23cd72 to your computer and use it in GitHub Desktop.
NSComboBox - fixed disappearing list
//
// FixedComboBox.swift
// Snippety
//
// Created by Wojciech Kulik on 03/09/2020.
// Copyright © 2020 Wojciech Kulik. All rights reserved.
//
import Cocoa
final class ClickView: NSView {
var onMouseDown: () -> (Bool) = { return false }
override func mouseDown(with event: NSEvent) {
if !onMouseDown() {
super.mouseDown(with: event)
}
}
}
/// https://stackoverflow.com/questions/63726518/nscombobox-closes-immediately-after-click
final class FixedComboBox: NSComboBox {
private let clickView = ClickView()
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
fix()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func awakeFromNib() {
super.awakeFromNib()
fix()
}
private func fix() {
clickView.onMouseDown = { [weak self] in
guard let cell = self?.cell else { return false }
// first expand will be immediately closed because of Cocoa bug
cell.setAccessibilityExpanded(true)
// we need to expand it again to fix the issue
// this one we schedule almost immediately to avoid blinking
DispatchQueue.main.async { cell.setAccessibilityExpanded(true) }
// in case the first one didn't "catch" the right moment (sometimes it happens)
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) { cell.setAccessibilityExpanded(true) }
return true
}
addSubview(clickView)
clickView.snp.makeConstraints { make in
make.width.equalTo(20)
make.trailing.top.bottom.equalToSuperview()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment