ios - 使用插入图像自定义 UINavigationBar

标签 ios swift autolayout uinavigationbar

customNavBar

我有这个导航栏,我正在尝试实现它,它看起来像这样: 我知道我可以将图像直接放在导航栏中或作为其下方的标题图像,但我不知道如何插入它以便它既包含在主容器 View 中又包含在导航栏中。

任何想法都会有所帮助!

最佳答案

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

  1. background:会匹配导航栏框架

enter image description here

  1. icon:假设图像 50x50 以 x 轴和 y 轴的背景为中心,其高度偏移量为 2.0

enter image description here

然后您可以尝试使用自动布局约束:

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


关于您的场景,您可能只需要图​​标和具有适当背景颜色的导航栏。但是,我添加了两个自动布局配置,因为这可能对其他人有用,尤其是当导航栏的背景非常复杂且带有边框、装饰等时。

关于ios - 使用插入图像自定义 UINavigationBar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48531300/

相关文章:

ios - 在 Swift 5 (iOS 12) 中写入磁盘时出错

ios - Swift - 向 UITextfield 添加带有间距的底线

ios - Swift 4 中的布局 anchor

ios - ScrollView 不会快速滚动

ios - NSDateFormatter格式化后错误的字符串

ios - Square API + iOS : OAuth not working?

ios - 以编程方式将 AutoLayout 用于搜索栏和 UITableView

ios - 将 UITableViewCell 保持在其他单元格的前面

swift - RTL iOS9 上奇怪的 UITextField 占位符行为

ios - ARKit - 在相机上居中 SCNode