为什么以编程方式设置我的宽高比约束未激活?
我简化了我的问题,使其像ViewController上的UIView一样,如下图所示:
I simplify my problem to be like just an UIView on ViewController like the image below:
我将纵横比约束从情节提要板拖到ViewController代码中,并命名为aspectRatioConstraint
.
I drag the aspect ratio constraint from storyboard to ViewController code, and named aspectRatioConstraint
.
我希望运行应用程序时紫色视图的宽高比为1:1,所以在viewDidLoad中我设置了aspectRatioConstraint.constant = 1
(在运行宽高比之前为343:128)
I want that purple view will have the aspect ratio 1:1 when I run the app, so in viewDidLoad I set aspectRatioConstraint.constant = 1
(before running the aspect ratio is 343:128)
但是当我运行该应用程序时什么也没发生.宽高比未更改为1:1,这里出了什么问题?
but nothing happened when I run the app. the aspect ration doesn't change to 1:1, what went wrong in here ?
由于multiplayer
是仅获取属性,因此我们无法更改其值,而可以更改constant
属性.
As the multiplayer
is get only property we can't change its value instead we can change the constant
property.
open var multiplier: CGFloat { get }
从约束菜单中:
第一项=(乘数*第二项)+常量
First Item = (Multiplier * Second Item) + Constant
View.Height =((128/343)* View.Width)+ 0
View.Height = ((128/343) * View.Width) + 0
换句话说,343 = (0.373 * 128) + x
由于乘数必须从0.373更改为1
As multiplier has to be changed from 0.373 to 1
(View.Height - constant) / View.width = Multiplier
(343-x)/128 = 1
(343 - x) / 128 = 1
x = 343-128
x = 343 - 128
x = 215
aspectRatioConstraint.constant = 215
yourView.layoutIfNeeded()