Ios Swift 3新更新。为什么我的导航标题是更新前的两倍?

Ios Swift 3新更新。为什么我的导航标题是更新前的两倍?,ios,swift3,uiimage,uinavigationbar,Ios,Swift3,Uiimage,Uinavigationbar,我有一个图像设置为导航栏标题的应用程序。我有一个完美的尺寸,但自从我更新了我的iPhone和mac/xcode后,图像是图像的实际大小,而不是设置的大小。我该如何解决这个问题?谢谢 var titleView : UIImageView titleView = UIImageView(frame: CGRect(x: 0, y: 0, width: 32, height: 32)) titleView.contentMode = .scaleAspectFit titleView.imag

我有一个图像设置为导航栏标题的应用程序。我有一个完美的尺寸,但自从我更新了我的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
请像这样使用:

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

要添加稍微不同的操作方法,请执行以下操作:

使用autolayout时,不值得设置视图的框架,因为它们将在布局过程中被覆盖,所以我会这样做,添加注释以解释我的操作:

// 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

完美的非常感谢。只是需要调整尺寸。