简体   繁体   中英

Swift programmatically place UIImageView on top of another and resize

On my storyboard I have 2 image views. One holds the main image, the second is an overlay which will be used to specify the crop area of the main image.

In my viewDidLoad I've done this.

let screen_width = UIScreen.mainScreen().bounds.width
let screen_height = UIScreen.mainScreen().bounds.height
self.overlayImage.frame = CGRect(x: self.imageView.frame.origin.x, y: self.imageView.frame.origin.y, width: screen_width, height: (screen_height * 0.1919))

The goal is to have the overlayImage's top left corner lined up properly with the imageView's top left corner. Also the height of the overlay should be about 1/5th of the screens size. However when I run the code the overlayImage is exactly the same size and in the same location it was originally on the storyboard.

How can I programmatically line it up on top of the imageView after the image has been set to it, and also resize the overlayImage dynamically in the viewDidload? I'd just do it manually in storyboard editor but everyone will have different screen sizes so I thought it best to use the mainscreen().bounds.height variable to determine the amount of height to use dynamically at runtime.

All you have to do is to write your above code in viewDidAppear instead of viewDidLoad as below:-

override func viewDidAppear(animated: Bool) {
    let screen_width = UIScreen.mainScreen().bounds.size.width
    let screen_height = UIScreen.mainScreen().bounds.size.height
    self.overlayImage.frame = CGRect(x: 0, y: 0, width: screen_width, height:screen_height/5)
}

And your frame will set itself as desired.

Since you're working with Storyboard, I would rather use Autolayout and Constraints to solve this problem for me... For instance you set the constraints for your first image view, then set the constraints of your overlay based and related to the former one. Example:

  • Lower UIImageView: set leading, trailing, top and bottom constraints
  • Overlay: set center X and Y constraints to be equal to the lower Image
  • Overlay: set height and width to be proportional to the lower image

Thus, when ever the screen size changes, the two images will always resize equally...

Interface builder:

  1. Set overlay top, leading, width to your image view.
  2. give your overlay a constant height constraint; the constraint cosntant value is arbitrary because you will replace it at run time
  3. ctrl + drag an IBOutlet from this height constraint to your viewcontroller
  4. in your viewWillLayoutSubViews set the .constant of your height constraint to UIScreen.main.bounds.size.height / 5

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