//MARK: NSLayoutConstraints
//trailing
let trailingConstaint = NSLayoutConstraint(item: imageView, attribute: .trailing, relatedBy: .equal, toItem:imageView.superview , attribute: .trailing, multiplier: 1, constant: 0)
trailingConstaint.isActive = true
//leading
let leadingConstraint = NSLayoutConstraint(item: imageView, attribute: .leading, relatedBy: .equal, toItem: imageView.superview, attribute: .leading, multiplier: 1, constant: 0)
leadingConstraint.isActive = true
//top
let topConstraint = NSLayoutConstraint(item: image, attribute: .top, relatedBy: .equal, toItem: imageView.superview, attribute: .top, multiplier: 1, constant: 0)
topConstraint.isActive = true
//bottom
let bottomConstraint = NSLayoutConstraint(item: imageView, attribute: .bottom, relatedBy: .equal, toItem: imageView.superview, attribute: .bottom, multiplier: 1, constant: 0)
bottomConstraint.isActive = true
我想调整图像大小使其适合,以便正确缩放图像 screenshot of ViewController
但是我得到这个错误..
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'NSLayoutConstraint for size {746, 496} orientation 0 scale 1.000000: Constraint items must each be an instance of UIView, or UILayoutGuide.'
最佳答案
//top
let topConstraint = NSLayoutConstraint(item: image, attribute: .top, relatedBy: .equal, toItem: imageView.superview, attribute: .top, multiplier: 1, constant: 0)
topConstraint.isActive = true
您将此约束设置为 image 而不是 imageView。
异常明确指出约束项必须每个都是 UIView 或 UILayoutGuide 的实例。'
所有其他约束都设置在 imageView 和 imageView.superView 之间,因此从逻辑上讲,上述约束也应该使用同一对。
这将处理异常。
//top
let topConstraint = NSLayoutConstraint(item: imageView, attribute: .top, relatedBy: .equal, toItem: imageView.superview, attribute: .top, multiplier: 1, constant: 0)
topConstraint.isActive = true
但是,图像缩放不能通过约束来实现。您必须适本地设置 contentMode 属性。查看 well-explained docs. 中的了解图像的缩放方式部分
关于ios - NSLayoutConstraint问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48456677/