Maschina
Maschina

Reputation: 926

Changing height of NSSearchField in SwiftUI

I am working with SwiftUI 1.0.

I have created a search bar for SwiftUI as the following:

import SwiftUI

struct Searchbar: NSViewRepresentable {
    class Coordinator: NSObject, NSSearchFieldDelegate {
        var parent: Searchbar
        
        init(_ parent: Searchbar) {
            self.parent = parent
        }
        
        func controlTextDidChange(_ notification: Notification) {
            guard let searchField = notification.object as? NSSearchField else {
                log.error("Unexpected control in update notification", source: .ui)
                return
            }
            self.parent.search = searchField.stringValue
        }
    }
    
    @Binding var search: String
    
    func makeNSView(context: Context) -> NSSearchField {
        let searchfield = NSSearchField(frame: .zero)    
        return searchfield
    }
    
    func changeSearchFieldItem(searchfield: NSSearchField, sender: AnyObject) -> NSSearchField {
        //Based on the Menu item selection in the search field the placeholder string is set
        (searchfield.cell as? NSSearchFieldCell)?.placeholderString = sender.title
        return searchfield
    }
    
    func updateNSView(_ searchField: NSSearchField, context: Context) {
        searchField.stringValue = search
        searchField.delegate = context.coordinator
    }
    
    func makeCoordinator() -> Coordinator {
        return Coordinator(self)
    }
}

This is working fine so far when using it in my View: Searchbar(search: $searchText)

enter image description here

I am wondering if the height of the NSSearchField can be changed to have a view similar to what is seen in the Maps.app: enter image description here

Upvotes: 2

Views: 557

Answers (1)

Frank R
Frank R

Reputation: 891

Update: You can also set the controlSize to .large if you’re on Big Sur. https://developer.apple.com/documentation/appkit/nscontrol/controlsize/large


You can add a height constraint:

func makeNSView(context: Context) -> NSSearchField {
    let searchfield = NSSearchField(frame: .zero)  
    searchfield.translatesAutoresizingMaskIntoConstraints = false
    searchfield.heightAnchor.constraint(greaterThanOrEqualToConstant: 40).isActive = true

    return searchfield
}

…which works in macOS 11.1 Big Sur. Unfortunately the Focus ring does not adapt its height. You could hide it like this:

    searchTextField.focusRingType = .none

… but that does not seem desirable in most situations.

Upvotes: 3

Related Questions