导航栏中的图像有点太大而且重叠在导航栏之外。我想缩小图像以适应条形图。我现在的代码是:
let banner = UIImage(named: "banner.png")
let imageView = UIImageView(image:banner)
imageView.contentMode = UIViewContentMode.ScaleAspectFit
self.navigationItem.titleView = imageView
但ScaleAspectFit似乎不起作用。
编辑:我通过添加框架更新了我的问题:
let banner = UIImage(named: "banner.png")
let imageView = UIImageView(image:banner)
var bannerWidth = navigationItem.titleView!.frame.width
var bannerHeight = navigationItem.titleView!.frame.height
var bannerx = navigationItem.titleView!.frame.size.width / 2 - banner!.size.width / 2
var bannery = navigationItem.titleView!.frame.size.height / 2 - banner!.size.height / 2
imageView.frame = CGRect(x: bannerx, y: bannery, width: bannerWidth, height: bannerHeight)
imageView.contentMode = UIViewContentMode.Center
self.navigationItem.titleView = imageView
但我现在收到错误
fatal error: unexpectedly found nil while unwrapping an Optional value
在bannerWidth变量声明中。
答案 0 :(得分:0)
但ScaleAspectFit似乎不起作用
确实有效。问题是您没有提供任何比例来缩放到。您尚未imageView
frame
。因此它是原始图像的大小,它太大了。正如你自己所说,你需要缩小它。通过为图像视图提供frame
来缩放图像视图,或者通过将图像缩小来缩放图像。
答案 1 :(得分:0)
想出来!使用了错误的导航代码
let banner = UIImage(named: "banner.png")
let imageView = UIImageView(image:banner)
var bannerWidth = navigationController?.navigationBar.frame.size.width
var bannerHeight = navigationController?.navigationBar.frame.size.height
var bannerx = bannerWidth! / 2 - banner!.size.width / 2
var bannery = bannerHeight! / 2 - banner!.size.height / 2
imageView.frame = CGRect(x: bannerx, y: bannery, width: bannerWidth!, height: bannerHeight!)
imageView.contentMode = UIViewContentMode.ScaleAspectFit
self.navigationItem.titleView = imageView
答案 2 :(得分:0)
要调整图像的大小,请尝试修改navigationItem.titleView的约束,它对我有用。
let banner = UIImage(named: "banner")
let bannerView = UIImageView(image: banner)
bannerView.contentMode = UIViewContentMode.ScaleAspectFit
self.navigationItem.titleView = bannerView
NSLayoutConstraint.activate([self.navigationItem.titleView!.heightAnchor.constraint(equalToConstant: 22),self.navigationItem.titleView!.widthAnchor.constraint(equalToConstant: 128)])