1

这听起来并不难,但经过数小时的尝试,我无法找到合适的解决方案。

问题:我想设置约束(使用 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

我真的很感激一个提示,如何做到这一点。提前致谢 :))

4

1 回答 1

6

完成这项工作的关键是将其宽度设置为colorImageView等于其父视图的宽度,但优先级为 750(而不是默认的 1000)。

然后将其高度设置为colorImageView其父lessThanOrEqualTo视图的高度。

Auto Layout 会尽力满足这两个新的约束。

当视图的宽度大于它的高度时,它将无法使colorImageViews 的宽度等于视图的宽度,但这没关系,因为优先级是 750。它会在不违反其他完全优先级的情况下使其尽可能大约束。

当视图的高度大于其宽度时,它将能够满足所有约束,因为 colorView 的高度就是lessThanOrEqualTo视图的高度。

import UIKit

let view = UIView(frame: CGRect(x: 0, y: 0, width: 80, height: 100))
view.backgroundColor = .red

let colorImageView = UIView()
colorImageView.translatesAutoresizingMaskIntoConstraints = false
colorImageView.backgroundColor = .yellow

view.addSubview(colorImageView)

// CREATE CONSTRAINTS(center in SuperView)
colorImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
colorImageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

// CREATE CONSTRAINTS (ratio 1:1)
colorImageView.widthAnchor.constraint(equalTo: colorImageView.heightAnchor, multiplier: 1.0).isActive = true

let widthConstraint = colorImageView.widthAnchor.constraint(equalTo: view.widthAnchor)
widthConstraint.priority = UILayoutPriority(rawValue: 750)
widthConstraint.isActive = true

colorImageView.heightAnchor.constraint(lessThanOrEqualTo: view.heightAnchor).isActive = true

view.layoutIfNeeded()

view.frame = CGRect(x: 0, y: 0, width: 60, height: 50)
view.layoutIfNeeded()

它在 Playground 中运行:

在此处输入图像描述

于 2016-11-07T03:57:09.777 回答