菜鸟教程小白 发表于 2022-12-11 18:14:39

ios - 如何在导航栏中正确设置图像的约束?


                                            <p><p>在导航栏中设置图像有数千种解释,但恕我直言,它们都有相同的问题:它们为 <code>UIImageView</code> 使用固定高度,但如果您旋转设备<code>navigationBar</code>-height 变小,图片太高。我试图用约束来解决这个问题,但我失败了:</p>

<pre><code>let imageView = UIImageView( image: UIImage( named: &#34;logo.png&#34; ) )
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 ] )
</code></pre>

<p>它在横向模式下不起作用!</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>在这种情况下,您不需要设置约束。导航 Controller 的标题 View 具有水平和垂直居中的默认约束,具有固定的宽度和高度。所以你需要做的就是在你的 View 中设置框架大小并加载</p>

<pre><code>let imageView = UIImageView( image: UIImage( named: &#34;aaa.png&#34; ) )
var frame = imageView.frame
frame.size.height = 30
frame.size.width = 30
imageView.frame = frame
imageView.contentMode = .scaleAspectFit

self.navigationItem.titleView = imageView
</code></pre>

<p>然后添加一个监听器以检测方向变化并相应地更改帧大小。 </p>

<pre><code>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
}
</code></pre>

<p>结果是这样的</p>

<p> <a href="/image/sCitL.gif" rel="noreferrer noopener nofollow"><img src="/image/sCitL.gif" alt="enter image description here"/></a> </p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 如何在导航栏中正确设置图像的约束?,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/45033361/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/45033361/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 如何在导航栏中正确设置图像的约束?