这听起来并不难,但经过数小时的尝试,我无法找到合适的解决方案。
问题:我想设置约束(使用 NSLayoutAnchor 类)以使子视图(colorImageView)在父视图中居中,纵横比为 1:1并且始终在有时具有宽度 > 高度的父视图中可能的最大尺寸或高度 > 宽度。
示例 1:SuperViewSize = width : 80, height = 100 -> 子视图的高度和宽度应为 80 并以 (40/50) 为中心
示例 2:SuperviewSize = width : 60, height = 50 -> 子视图的高度和宽度应为 50 并以 (30/25) 为中心
我不想/它不能解决问题/硬编码 widthConstraint = min(superviewWidth, superviewHeight) 因为在创建子视图时,最终没有定义超级视图边界->所以我需要一个约束。
这是我迄今为止的尝试(仍然缺少在不同的超级视图中将高度和宽度设置为最大可能的约束:
// CREATE CONSTRAINTS(center in SuperView)
colorImageView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
colorImageView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
// CREATE CONSTRAINTS (ratio 1:1)
colorImageView.widthAnchor.constraint(equalTo: colorImageView.heightAnchor, multiplier: 1.0).isActive = true
我真的很感激一个提示,如何做到这一点。提前致谢 :))