【问题标题】:Applying Constraints Programmatically to UIImageView Subview以编程方式将约束应用于 UIImageView 子视图
【发布时间】:2019-05-22 18:45:24
【问题描述】:
  1. 我有一个 uiview,它使用 autolayout 约束调整大小。
  2. 我有一个uiimageview,我将它作为subview 插入,然后在数据库中存储从前/后/上/下边缘到uiview 超级视图的距离。 另一个注意事项是原始的uiimageview 可以转换和翻译,所以CGPoint、CGAffineTransform 和CGRect 也被保存。
  3. 我从数据库中获取每条边的这些“常量”值,然后以编程方式将约束激活到实例化的uiimageview,以复制插入的原始uiimageview。

我添加约束的原因是uiimageview 能够成比例地适应uiview 大小的变化。

我的问题是我的代码有些古怪,我无法根据我存储、获取然后重新应用的数据来解决为什么我无法重现原始 uiimageview。

当谈到以编程方式使用约束时,我承认我很迷茫,如果有任何帮助,我将不胜感激。

//Storing constraint constants of original uiimageview in original container uiview
let leadingConstraint = originalImageView.frame.minX
let trailingConstraint = oldContainer.frame.maxX - originalImageView.frame.maxX
let topConstraint = originalImageView.frame.minY
let bottomConstraint = oldContainer.frame.maxY - originalImageView.frame.maxY

//Fetching and applying constants to new uiimageview in new container uiview (Separate operation from the above! Above takes place first!)

newImageView.bounds = CGRect(x: 0, y: 0, width: 80, height: 80)
newImageView.center = CGPoint(x: saved.x, y: saved.y)
newImageView.transform = CGAffineTransform(a: saved.a, b: saved.b, c: saved.c, d: saved.d, tx: saved.tx, ty: gifForm.ty)

newContainer.insertSubview(newImageView, at: 0)

newImageView.translatesAutoresizingMaskIntoConstraints = false
let leadingConstraint = newImageView.leadingAnchor.constraint(equalTo: newContainer.leadingAnchor, constant: saved.leadingConstant)
let trailingConstraint = newImageView.trailingAnchor.constraint(equalTo: newContainer.trailingAnchor, constant: -saved.trailingConstant)
let topConstraint = newImageView.topAnchor.constraint(equalTo: newContainer.topAnchor, constant: saved.topConstant)
let bottomConstraint = newImageView.bottomAnchor.constraint(equalTo: newContainer.bottomAnchor, constant: -saved.bottomConstant)
NSLayoutConstraint.activate([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint])

【问题讨论】:

  • 可能是在玩变换破坏约束逻辑,所以所有计算都不会准确
  • @Sh_Khan 是的,我注释掉了变换,它更接近原始图像......但由于旋转或水平翻转图像,我确实需要变换......有什么方法可以覆盖还是以合作的方式使用它们?

标签: ios swift uiimageview constraints nslayoutconstraint


【解决方案1】:

尝试仅使用任一约束(将translatesAutoresizingMaskIntoConstraints 设置为false)或不使用(保留true)。

您不能同时使用两者,这意味着如果您打算使用约束,则不能使用 .center 之类的东西,而必须使用 centerXAnchor 和 centerYAnchor 之类的对应项。

也不确定这是否只是疏忽,但最后的四行使用与上面相同的属性名称。

【讨论】:

  • 是的,请注意,这就是设置转换与约束冲突的问题。有没有办法并行使用它们?我需要使用变换来对图像应用诸如旋转之类的东西,但也想使用约束,以便它与超级视图成比例地缩放。 @Sean C. Li
  • @Chris 尝试完全切换到约束,使用约束将heightAnchor 直接关联到widthAnchor 以模仿transform。如果它导致奇怪的比例,您还可以将图像视图的contentMode 调整为aspectFill。另一方面,您可以专门使用另一种方法,如果需要,这确实更容易 IMO 实现和动画,但我更喜欢约束。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多