我有这个导航栏,我正在尝试实现它,它看起来像这样: 我知道我可以将图像直接放在导航栏中或作为其下方的标题图像,但我不知道如何插入它以便它既包含在主容器 View 中又包含在导航栏中。
任何想法都会有所帮助!
最佳答案
我想这可以使用两张图片来实现:
- background:会匹配导航栏框架
- icon:假设图像 50x50 以 x 轴和 y 轴的背景为中心,其高度偏移量为 2.0
然后您可以尝试使用自动布局约束:
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 上结果是:
关于您的场景,您可能只需要图标和具有适当背景颜色的导航栏。但是,我添加了两个自动布局配置,因为这可能对其他人有用,尤其是当导航栏的背景非常复杂且带有边框、装饰等时。
关于ios - 使用插入图像自定义 UINavigationBar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48531300/