简体   繁体   中英

Add UIView in navigation bar

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!

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"))

From Storyboard,

  1. You have ViewController with navigationController

在此处输入图片说明

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

在此处输入图片说明

  1. Take a UIView (purpleView) with constraints

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

    • top= 20 (for status bar)
    • leading trailing bottom= 0 wrt 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.

How about to make it as a normal UIView and hide the navBar and show it in the next VC, who will know which trick you have used. read this short article here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM