如何在导航栏中更改titleView的大小.因为navigationBar中的titleView和backButton之间存在间隙 [英] How to change the size of titleView in navigation bar. Because there's a gap between titleView and backButton in navigationBar

查看:341
本文介绍了如何在导航栏中更改titleView的大小.因为navigationBar中的titleView和backButton之间存在间隙的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在我的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 ButtonSearchBar之间存在间隙,如下所示:

But then there're gap between Back Button and SearchBar, like this:

我认为在这里出现间隙是因为backBarButtonItemtitle留有空间(因为我的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之间存在间隙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆