使用插入图像

时间:2018-01-30 22:05:39

标签: ios swift autolayout uinavigationbar

customNavBar

我有这个导航栏我试图实现,如下所示: 我知道我可以将图像直接放在导航栏中,也可以作为它下面的标题图像,但我不知道如何插入它以便它包含在主容器视图中并且也会破坏导航栏。 / p>

任何想法都会有所帮助!

1 个答案:

答案 0 :(得分:1)

我猜这可以使用两张图片实现:

  1. 背景:将与导航栏框架匹配
  2. enter image description here

    1. 图标:让我们说一个50x50的图像以x轴为背景,y轴偏离其高度/ 2.0
    2. enter image description here

      然后您可以尝试使用autolayout约束:

      import UIKit
      
      class ViewController: UIViewController {
      
          override func viewDidLoad() {
              super.viewDidLoad()
      
              guard let navbar = self.navigationController?.navigationBar else {return} // be sure to have defined a navigation controller
              navbar.clipsToBounds = false // so the icon will be visible outside the nav bar
      
              let niceBkg = UIImageView(image: UIImage(named: "bkg"))
              navbar.addSubview(niceBkg)
              niceBkg.translatesAutoresizingMaskIntoConstraints = false
              niceBkg.leftAnchor.constraint(equalTo: navbar.leftAnchor).isActive = true
              niceBkg.rightAnchor.constraint(equalTo: navbar.rightAnchor).isActive = true
              niceBkg.topAnchor.constraint(equalTo: self.navigationController!.view.topAnchor).isActive = true
              niceBkg.bottomAnchor.constraint(equalTo: navbar.bottomAnchor).isActive = true
      
              let niceIcon = UIImageView(image: UIImage(named: "icon"))
              niceBkg.addSubview(niceIcon)
              niceIcon.translatesAutoresizingMaskIntoConstraints = false
              niceIcon.widthAnchor.constraint(equalToConstant: 50).isActive = true
              niceIcon.heightAnchor.constraint(equalToConstant: 50).isActive = true
              niceIcon.centerXAnchor.constraint(lessThanOrEqualTo: niceBkg.centerXAnchor).isActive = true
              niceIcon.bottomAnchor.constraint(greaterThanOrEqualTo: niceBkg.bottomAnchor, constant: 25).isActive = true
          }
      }
      
      iPhoneX上的

      结果是:

      enter image description here

      关于您的方案,您可能只需要具有适当背景颜色的图标和navigationBar。但是我添加了两个自动布局配置,因为它可能对其他人有用,特别是如果navigationBar的背景与边框,装饰等相当复杂。