问题描述
我已经在我的navigation.titleView中添加了搜索栏
I've added a search bar to my navigation.titleView
self.navigationItem.titleView = searchBar
还有一个标题为"的BackBarButtonItem
There's also a BackBarButtonItem with title = ""
self.navigationItem.backBarButtonItem?.title = ""
但是在Back Button
和SearchBar
之间存在间隙,如下所示:
But then there're gap between Back Button
and SearchBar
, like this:
我认为在这里出现间隙是因为backBarButtonItem
的title
留有空间(因为我的title
为空",但空间仍然存在)
I Think that the gap appears here because there's space for title
of backBarButtonItem
(because my title
is null "" but the space still there)
所以我想问一下如何缩小这个差距?我想使我的searchBar
靠近我的backBarIcon
So I want to ask how to omit that gap? I want to make my searchBar
nearer my backBarIcon
非常感谢您!
我尝试更改searchBar的框架,但无法正常工作
EDIT 1:I try to change searchBar's frame but it's not working
这是我的代码
//Change searchBar's frame
let titleViewFrame = (searchController.searchBar.frame)
searchController.searchBar.frame = CGRect(x: titleViewFrame.minX - 20.0, y: titleViewFrame.minY, width: titleViewFrame.width + 20.0, height: titleViewFrame.height)
推荐答案
override func viewDidLoad() {
super.viewDidLoad()
let container = UIView(frame: CGRect(x: 0, y: 0, width: 1000, height: 22))
let searchBar = UISearchBar()
searchBar.translatesAutoresizingMaskIntoConstraints = false
container.addSubview(searchBar)
let leftButtonWidth: CGFloat = 35 // left padding
let rightButtonWidth: CGFloat = 75 // right padding
let width = view.frame.width - leftButtonWidth - rightButtonWidth
let offset = (rightButtonWidth - leftButtonWidth) / 2
NSLayoutConstraint.activate([
searchBar.topAnchor.constraint(equalTo: container.topAnchor),
searchBar.bottomAnchor.constraint(equalTo: container.bottomAnchor),
searchBar.centerXAnchor.constraint(equalTo: container.centerXAnchor, constant: -offset),
searchBar.widthAnchor.constraint(equalToConstant: width)
])
self.navigationItem.titleView = container
}
这篇关于如何在导航栏中更改titleView的大小.因为navigationBar中的titleView和backButton之间存在间隙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!