ios - 如何更改导航栏中 titleView 的大小。因为在 navigationBar 的 titleView 和 backButton 之间有一个空隙

标签 ios swift navigationbar

我已经在我的 navigation.titleView 中添加了一个搜索栏

    self.navigationItem.titleView = searchBar

还有一个带有 title = ""的 BackBarButtonItem

    self.navigationItem.backBarButtonItem?.title = ""

但是 Back ButtonSearchBar 之间存在间隙,如下所示: There're gap between Back Button and SearchBar

我认为这里出现间隙是因为 backBarButtonItemtitle 有空间(因为我的 title 是 null ""但空间仍然那里)

所以我想问一下如何省略那个间隙?我想让我的 searchBar 更靠近我的 backBarIcon

非常感谢!

编辑 1: 我尝试更改 searchBar 的框架,但它不起作用

这是我的代码

    //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
}

enter image description here

关于ios - 如何更改导航栏中 titleView 的大小。因为在 navigationBar 的 titleView 和 backButton 之间有一个空隙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42430430/

相关文章:

ios - 如何检查解析 Xcode 中获取的用户名

iphone - ID : Library not found for -lMBProgressHUD

ios - 如何获取 Sprite Kit 中 UI 触摸的位置?

ios - UITextField 的自定义输入 View 的 WindowLevel

html - 从第一项单独出现的无序列表创建下拉菜单

html - 导航栏在一个页面上有效,但在另一个页面上无效

ios - 如何使用swift仅在iPhone中以横向显示 Split View

ios - 如何在swift中添加长文本阴影?

Swift:将变量插入标签?

ios - 自定义 UINavigationBar