Search code examples
swiftcocoansviewnssearchfield

OSX Cocoa NSSearchField clear button not responding to click


I place an NSSearchField and set its border to none and I found that the clear button is not clickable a.k.a. not responding when clicked. If I set the border again it's working fine.

enter image description here

I've been debugging this for a few hours, and found out that when I set the border to none, the text editor width will expand and shadow (cover) the clear button.

Screenshot

enter image description here

View hierarchy debug screenshot

enter image description here

Steps to reproduce:

  1. Create an empty cocoa project/app
  2. Place an NSSearchField
  3. Set border to none
  4. Run the app, fill the search field and try to click the clear button

Is this a bug? Or is it intended to behave that way?

Note: Newbie in cocoa development


Solution

  • I faced with this problem and deemed it as a bug in Cocoa. But it is easy to fix in custom control or in a view controller. Just keep text field bordered in interface builder and then kill the border by having new CALayer. For example:

    class ViewController: NSViewController {
    
    
    @IBOutlet weak var searchField: NSSearchField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        let maskLayer = CALayer()
        searchField.layer = maskLayer
        maskLayer.backgroundColor = searchField.backgroundColor?.CGColor
    }
    }
    

    As you see, I am just restoring control color in new layer not preserving anything else. It is not perfect, but at least gives good start.