在导航栏中设置图像有数千种解释,但恕我直言,它们都有相同的问题:它们为 UIImageView 使用固定高度,但如果您旋转设备navigationBar -height 变小,图片太高。我试图用约束来解决这个问题,但我失败了:
let imageView = UIImageView( image: UIImage( named: "logo.png" ) )
imageView.contentMode = .scaleAspectFit
self.navigationItem.titleView = imageView
let height = NSLayoutConstraint(
item: imageView, attribute: .height,
relatedBy: .equal,
toItem: self.navigationItem.titleView, attribute: .height,
multiplier: 1, constant: 0
)
NSLayoutConstraint.activate( [ height ] )
它在横向模式下不起作用!
Best Answer-推荐答案 strong>
在这种情况下,您不需要设置约束。导航 Controller 的标题 View 具有水平和垂直居中的默认约束,具有固定的宽度和高度。所以你需要做的就是在你的 View 中设置框架大小并加载
let imageView = UIImageView( image: UIImage( named: "aaa.png" ) )
var frame = imageView.frame
frame.size.height = 30
frame.size.width = 30
imageView.frame = frame
imageView.contentMode = .scaleAspectFit
self.navigationItem.titleView = imageView
然后添加一个监听器以检测方向变化并相应地更改帧大小。
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
let imageView = self.navigationItem.titleView!
var frame = imageView.frame
if UIDevice.current.orientation.isLandscape {
frame.size.height = 10
frame.size.width = 10
} else {
frame.size.height = 30
frame.size.width = 30
}
imageView.frame = frame
}
结果是这样的
关于ios - 如何在导航栏中正确设置图像的约束?,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/45033361/
|