如何在 Swift Xcode 中创建自定义导航栏?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47032929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 10:23:46  来源:igfitidea点击:

How to create a custom navigation bar in Swift Xcode?

iosswiftxcodeuinavigationcontroller

提问by Caspert

I am working on a chat app for my graduation project in iOS. I designed the following navigation bar:

我正在为我的 iOS 毕业项目开发聊天应用程序。我设计了以下导航栏:

enter image description here

在此处输入图片说明

Now I am trying to develop above graphic in my Xcode project, but I don't know if this is the correct way to achieve this and doesn't get it like the graphic.

现在我试图在我的 Xcode 项目中开发上面的图形,但我不知道这是否是实现这一目标的正确方法,并且不像图形那样得到它。

I am using a xib file, that I load in my ViewController.swiftusing an instance of it. Than add it as the titleViewof the navigationItem:

我正在使用一个 xib 文件,我ViewController.swift使用它的一个实例加载该文件。比将其添加为titleViewnavigationItem

let helperView = HelperView()
navigationItem.titleView = helperView

This is the result of above code snippet:

这是上面代码片段的结果:

enter image description here

在此处输入图片说明

The problem of this result is that it is overlapping the left bar button item and another problem, that I still doesn't figured out is, if the message bubble can have a dynamic height, when it have multiple lines (max is 3 lines).

这个结果的问题是它与左栏按钮项目重叠,另一个我仍然没有弄清楚的问题是,如果消息气泡可以具有动态高度,当它有多行时(最大为3行) .

enter image description here

在此处输入图片说明

Does anyone have experience with this kind of design within Xcode and is this the correct way to do this, or is there a better way to achieve this. Maybe a custom UINavigationController class?

有没有人在 Xcode 中使用过这种设计,这是正确的方法,还是有更好的方法来实现这一点。也许是自定义 UINavigationController 类?

回答by Tj3n

Try create the whole navigation view that you desire, that mean the width is equal to the view, then try use this code to add it

尝试创建您想要的整个导航视图,这意味着宽度等于视图,然后尝试使用此代码添加它

    navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
    navigationController?.navigationBar.shadowImage = UIImage()
    navigationController?.navigationBar.backgroundColor = .clear

    navigationController?.view.insertSubview(subview, belowSubview: navigationController?.navigationBar)

It will makes your navigation bar become invisible but still showing the bar button

它会使您的导航栏变得不可见,但仍显示栏按钮

Update, by dimpiax

更新,由dimpiax

But better to override your UINavigationController class, and setup view in viewDidLoad

但最好覆盖您的 UINavigationController 类,并在 viewDidLoad

navigationBar.shadowImage = UIImage()
navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationBar.backgroundColor = .clear

And on dependent viewController's view – show specific view.

并在依赖 viewController 的视图上 - 显示特定视图。