evenwerk
evenwerk

Reputation: 987

Swift - UISearchBar in UIToolbar

How can I create A UISearchBar inside of a Toolbar in Swift? If I use the Interface Builder I get the following error:

error: Illegal Configuration: UISearchBar embedded in UIBarButtonItems (Only available in iPad documents)

Is there a Swift solution for this problem? The Toolbar will only be available on iPad.

Upvotes: 0

Views: 2093

Answers (1)

Rob Norback
Rob Norback

Reputation: 6599

UIToolBar is just a custom UIView, so you have three options (that I can see) for your implementation:

First, if you want to stick the search bar in the toolbar here's the code:

var searchBar = UISearchBar(frame: CGRectMake(0, 0, 100, 50))
var myView = UIView(frame: searchBar.frame)
myView.addSubview(searchBar)
var barButtonItem = [UIBarButtonItem(customView: myView)]
toolBar.setItems(barButtonItem, animated: false)

Second, if you want the search bar in the nav bar on your screen you can do the following:

let searchBar = UISearchBar(frame: CGRectMake(0, 0, 300, 50)) 
navigationController?.navigationBar.addSubview(searchBar)

Third, if you need the toolbar to be elsewhere, you can create your own custom UIView that looks like a toolbar (spans the width of the screen) and add the search bar to that. You can even make this new toolbar of yours a custom class so it's reusable throughout your program.

Cheers!

Upvotes: 2

Related Questions