我想暂时关闭自动布局并使用其 bounds
处理 UIView 的大小和位置, center
, 和 transformation
.
我有一个非常简单的“单 View 应用程序”示例。我的应用程序有一个托管主视图的 View Controller 。在那个 View 中有两个按钮,另一个 View (背景设置为粉红色)又包含一个 ImageView (设置为宽高比):
我已经将我的问题提炼成一个非常简单的 UIViewController:
@IBOutlet weak var imageHolderView: UIView!
@IBOutlet weak var imageView: UIImageView!
@IBAction func loadImageButtonClicked(sender: AnyObject) {
let url = NSURL(string: "https://c2.staticflickr.com/4/3909/15110089915_21a12eba6a_k.jpg")
let data = NSData(contentsOfURL: url!)
self.imageView.image = UIImage(data: data!)
}
@IBAction func clearConstraintsButtonClicked(sender: AnyObject) {
let bounds:CGRect = self.imageHolderView.bounds
let center:CGPoint = self.imageHolderView.center
NSLayoutConstraint.deactivateConstraints(self.imageHolderView.constraints)
self.imageHolderView.bounds = bounds
self.imageHolderView.center = center
}
注意我试图在一个更复杂的项目中理解这一点,这里的例子只是为了演示这个问题。
当我运行该项目时,图像没有来源,因此粉红色的 UIView ( imageHolderView
) 按预期占据了大部分屏幕:
当我单击加载图像按钮时, Controller 将图像从网络加载到 UIImageView 中。因为约束仍然存在,所以自动布局确保图片在方面适合 UIImageView 约束到它的 super View imageHolderView
:
如果我现在清除约束,我希望看不到任何区别,因为自动布局设置的约束会立即在代码中被相同的值替换。但这不是我所看到的:
如何获取由自动布局设置的 UIView 的边界和中心,关闭 UIView 的自动布局,然后从我自己的 swift 代码重新建立边界和中心?
在调试器中查看 UIView 的边界 imageHolderView
是正确的,并且对 UIImageView 的约束 imageView
几乎 (*) 仍然存在(我希望这会限制 UIImageView 以适应 UIView 内部),但 UIImageView 上的边界已经扩大以容纳全尺寸图像。为什么?
(在更复杂的应用程序中,我继续使用变换调整 View 大小、旋转和平移 View 。Apple's documentation 声明“如果变换属性包含非恒等变换,则框架属性的值未定义并且不应修改。在这种情况下,您可以使用 center 属性重新定位 View 并使用 bounds 属性调整大小。“示例代码不使用转换,但正如我所说,我的真实代码使用;我认为阻止我设置框架。)
(*) 我说差不多,因为 UIImageView 上有四个约束,但在调试器中计数是两个。
最佳答案
有几件事你忘记了。
首先,在:
NSLayoutConstraint.deactivateConstraints(self.imageHolderView.constraints)
确保您没有停用所需的约束。例如。如果您对 imageHolderView
有宽度或高度限制,您可以使用此调用将其停用。
在:
let bounds:CGRect = self.imageHolderView.bounds
let center:CGPoint = self.imageHolderView.center
NSLayoutConstraint.deactivateConstraints(self.imageHolderView.constraints)
self.imageHolderView.bounds = bounds
self.imageHolderView.center = center
您正在获取 imageHolderView
的 bounds
和 center
然后您尝试将它们分配回 imageHolderView
。这是错误的,因为您停用了为 imageView
设置位置的约束。您不必更改 self.imageHolderView
的位置,因为它的约束保存在它的父 View 中。另一方面,self.imageView
可能已停用所有约束,因此您应该设置它的位置:
self.imageView.bounds = bounds
self.imageView.center = center
center
设置错误,因为 imageHolderView.center
是在其父 View 的坐标系中指定的。您应该根据 bounds
手动计算中心。
self.imageView.center = CGPointMake(bounds.size.width / 2, bounds.size.height / 2)
然而,最大的问题可能是,bounds
和 center
(或 frame
)在任何 View 中默认被忽略是从启用了自动布局的 Storyboard/xib 创建的。
您必须手动将 imageView.translatesAutoresizingMaskIntoConstraints
设置为 true
。否则 frame
将被布局管理器忽略。
关于swift - 为什么不设置 UIView 的边界将其大小限制为这些边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35657035/