问题描述
我一直在尝试以编程方式在 NSImageView
中调整图像的大小。似乎没有任何方法可以这样做。图像最终变得非常大,并且无法对其进行调整。我想将其调整为 40(宽度)乘 40(高度)。
这是以编程方式创建的图像视图:
let theImg: NSImageView = {
let imageView = NSImageView()
imageView.image = NSImage(named: "my-logo")
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
以下是图像的约束条件:
view.addSubview(theImg)
theImg.leftAnchor.constraint(equalTo: view.leftAnchor,constant: 280).isActive = true
theImg.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
theImg.topAnchor.constraint(equalTo: view.topAnchor,constant: 50).isActive = true
如果可能,我会感谢那些愿意提供帮助或至少提供一些提示的人。
解决方法
您可以像这样将其添加到您的约束中:
NSLayoutConstraint.activate([
theImg.leadingAnchor.constraint(equalTo: view.leadingAnchor,constant: 280),theImg.centerXAnchor.constraint(equalTo: view.centerXAnchor),theImg.topAnchor.constraint(equalTo: view.topAnchor,constant: 50),theImg.widthAnchor.constraint(equalToConstant: 40),theImg.heightAnchor.constraint(equalToConstant: 40)
])
NSLayoutConstraint.activate
是激活/停用约束的更好方法,因为您可以使用一组约束并停用/激活它们,而不是一个一个设置 isActive
。
此外,除非您希望左/前导约束在左侧,甚至是从右到左的语言,否则您应该使用 leadingAnchor
而不是 leftAnchor
。
More info