Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

uinavigationbar - iOS 11 SearchBar in NavigationBar

With iOS 11 Apple has redesigned the UISearchBar by making the corners rounder and the height bigger. Adding a UISearchBar to the navigationBar is pretty simple by just setting it as the titleView of the navigationItem using navigationItem.titleView = searchBar.

However, in iOS 11 it does not seem to work anymore as expected. Have a look at the screens where we compare the same setup using iOS 10 and iOS 11

iOS 10 enter image description here

iOS 11 enter image description here

You can clearly see that the SearchBar increases the size of the NavigationBar but the bar buttons do not get aligned correctly. Also the searchBar does not use the available space on the left anymore.

Putting the searchBar into a wrapper view to get the cancel button on iPad as described here Cancel button is not shown in UISearchBar also does not seem work anymore since the searchBar is then not visible at all.

If anyone has similar issues or already knowns how to fix/improve this I would be very thankful.

This was built using Xcode 9 Beta 4. Maybe future releases will fix this issue.

UPDATE:

Since this does not get fixed we decided to use following solution. We added a new UIBarButtonItem to the NavBar which then presents a new ViewController where we only put a searchBar and nothing else into the NavBar which seems to work. Using the selected answer may be the best solution since Apple with iOS 11 wants us to use this new design even if it does not give us the result we originally wanted. Another way to possible solve this could be a custom SearchBar but this is another topic.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's a new searchController property on navigationItem in iOS 11.

https://developer.apple.com/documentation/uikit/uinavigationitem/2897305-searchcontroller

Use like this...

if #available(iOS 11.0, *) {
     navigationItem.searchController = searchController
} else {
     // Fallback on earlier versions
     navigationItem.titleView = searchController?.searchBar
}

In Objective-C the if statement looks like this:

if (@available(iOS 11.0, *)) {

On iOS 11, if you don't set navigationItem.hidesSearchBarWhenScrolling = false, the search bar may initially be hidden, unless the user scrolls down to reveal it. If you do set it to false, it appears stacked below where the title would go without the user having to scroll.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...