简体   繁体   English

Swift /如何根据屏幕尺寸更改自动约束值

[英]Swift / how to change autocontraint value depending on screen size

I am using an extension to identify the device. 我正在使用扩展程序来识别设备。 I have a UIImage that appears too large on an iPhone 5S. 我有一个UIImage在iPhone 5S上看起来太大。 I want to scale the constraint depending on the device. 我想根据设备缩放约束。 I want it to be like that: 我希望它像这样:

if modelName == "Simulator" {
    cell.eventsImageViewWidthContraint =  Original * 0.8
}

What is the right code to change the constraint size (at the moment 360), to about 0.8 this size. 什么是正确的代码才能将约束大小(目前为360)更改为该大小的约0.8。

It looks like you're constraining the width of the ImageView to be a constant at the moment. 看来您目前正在限制ImageView的宽度为常数。 There are 2 options I'd suggest as an alternative to using a constant. 我建议使用2个选项来代替使用常量。 I'll assume you're using Interface Builder. 我假设您正在使用Interface Builder。

  1. Constrain the left and right edges to a certain distance from the containing view. 将左边缘和右边缘约束到与包含视图相距一定距离的位置。
  2. Constrain the width to be a ratio of the width of the containing view. 将宽度限制为包含视图的宽度的比率。 This can be accomplished by ctrl+dragging from the image view to its containing view and choosing "Aspect Ratio." 这可以通过ctrl +从图像视图拖动到其包含的视图并选择“纵横比”来实现。 You can fine tune what dimensions you're enforcing a ratio on by clicking the constraint in Interface Builder and adjusting values in the Size Inspector. 您可以通过单击“界面生成器”中的约束并在“大小”检查器中调整值来微调执行比例的尺寸。

You can also try Size Classes to change the dimensions of views based on the general size of the screen. 您也可以尝试使用大小类来根据屏幕的常规大小更改视图的大小。

If you are using code follow the advice above. 如果您使用的是代码,请遵循上面的建议。 If you are looking for an easy solution in code get the frame of the size view and calculate using those numbers. 如果您正在寻找一种简单的代码解决方案,请获取尺寸视图的框架并使用这些数字进行计算。 For example: 例如:

yourView.bounds.width = 0.5 * yourRootView.bounds.width

This code sets the width of a view to half the width of its root view 此代码将视图的宽度设置为其根视图的宽度的一半

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM