【问题标题】:Swift 3 new update. Why is my navigation title double the size it was before the update?斯威夫特 3 新更新。为什么我的导航标题是更新前的两倍?
【发布时间】:2017-10-03 17:57:46
【问题描述】:
我有一个将图像设置为导航栏标题的应用。我拥有完美的尺寸,但自从我更新了我的 iPhone 和 mac/xcode 后,图像是图像的实际尺寸,而不是它设置的尺寸。我该如何解决?谢谢。
var titleView : UIImageView
titleView = UIImageView(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
titleView.contentMode = .scaleAspectFit
titleView.image = UIImage(named: "logo.png")
self.navigationItem.titleView = titleView
【问题讨论】:
标签:
ios
swift3
uiimage
uinavigationbar
【解决方案1】:
请这样使用:
var titleView : UIImageView
titleView = UIImageView(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
let widthConstraint = titleView.widthAnchor.constraint(equalToConstant: 32)
let heightConstraint = titleView.heightAnchor.constraint(equalToConstant: 32)
heightConstraint.isActive = true
widthConstraint.isActive = true
【解决方案2】:
添加一个稍微不同的方法:
使用自动布局时,不值得设置视图的框架,因为它们将在布局过程中被覆盖,所以我会这样做,添加 cmets 以解释我在做什么:
// Unless you are going to recreate the view, just use a let not a var.
// A UIImageView is a reference type, so you can still change the image to be displayed.
// Also, there is no point declaring a variable and then setting it on the next line, just do it all at once.
// Using the non-parameterised initialiser uses a zero frame for the rect.
let titleView = UIImageView()
// Since the view is being created in code and autolayout is going to be applied, you need to add this line to prevent layout conflicts.
titleView.translatesAutoresizingMaskIntoConstraints = false
// Configure the aspect ratio of the displayed image.
titleView.contentMode = .scaleAspectFit
// You don't need to keep a reference to the constraint unless you want to activate and deactivate it.
titleView.widthAnchor.constraint(equalToConstant: 32).isActive = true
// Now, since you want the image to be a square, you can create an layout anchor that specifies this requirement, rather than just duplicating the width value.
titleView.heightAnchor.constraint(equalTo: titleView.widthAnchor, multiplier: 1).isActive = true