为什么以编程方式设置我的宽高比约束未激活? [英] why my aspect ratio constraint is not activated when it is set programatically?

查看:58
本文介绍了为什么以编程方式设置我的宽高比约束未激活?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我简化了我的问题,使其像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()

这篇关于为什么以编程方式设置我的宽高比约束未激活?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆