简体   繁体   中英

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. 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.

It looks like you're constraining the width of the ImageView to be a constant at the moment. There are 2 options I'd suggest as an alternative to using a constant. I'll assume you're using 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." 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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