Add UIView in navigation bar

不打扰是莪最后的温柔 提交于 2019-12-11 15:21:37

问题


I want to create UINavigationBar with rounded corner. It will look like this

What I am thinking is I add UIView with rounded corner and insert it in navigation bar. So this is my code

let roundView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 44))
roundView.backgroundColor = UIColor.whiteBackground
roundView.roundCorners(corners: [.topLeft, .topRight], radius: 20)
navigationController?.navigationBar.insertSubview(roundView, at: 0)
setTitleTextColor(color: UIColor.black)

By the UI, this works well. But then my UIBarButtonItem is missing, it covered up by my custom view and couldn't be clicked. So my question is, how to add subview in navigation bar?

Thank you!


回答1:


Just not use UINavigation bar and create all by scratch. Is the easiest way. Otherwise you can try with pattern image:

navigationController?.navigationBar.backgroundColor = UIColor(patternImage: UIImage(named: "background.png"))



回答2:


From Storyboard,

  1. You have ViewController with navigationController

  1. Select navigationController and deselect the below selected option i.e. Show Navigation Bar visibility.

  1. Take a UIView (purpleView) with constraints

    • top, leading trailing = 0 w.r.t. superview
    • height = 64
  2. Take another UIView (whiteView) in purpleView with constraints

    • top= 20 (for status bar)
    • leading trailing bottom= 0 w.r.t. purpleView
  3. Now add cancel and label to your whiteview

  4. Now your UI Hierarchy is like below

  1. Take outlet of whiteView and make corner radius

Thats it.

If you'r not using storyboard then you can do same with code also. In this case you have to set frame of purpleView and whiteView instead of constraints.

Hope now its clear to you.



来源:https://stackoverflow.com/questions/46401024/add-uiview-in-navigation-bar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!