简体   繁体   中英

Center UIImageView inside UIView

So I have a UIImageView named currentEventImage that is inside an UIView blurryBackGround . I currently want to center the UIImageView in the UIView . Below is my current code

//Subviews will be added here
view.addSubview(blurryBackGround)
view.addSubview(currentEventImage)
view.addSubview(currentEventDate)

//Constraints will be added here
_ = blurryBackGround.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, paddingTop: 17, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: self.view.frame.width, height: 330)
currentEventImage.heightAnchor.constraint(equalToConstant: 330).isActive = true
currentEventImage.topAnchor.constraint(equalTo: blurryBackGround.topAnchor, constant: 5).isActive = true
currentEventImage.center = blurryBackGround.center
blurryBackGround.addSubview(currentEventImage)

Any idea how I would do that?

currentEventImage.center = blurryBackGround.convert(blurryBackGround.center, from: blurryBackGround.superview)

Tried this and it didn't work

You may want to try the following solution based on centerXAnchor and centerYAnchor (feel free to remove constraints on width/height):

import UIKit

class ViewController: UIViewController {
    @IBOutlet var niceIcon:UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        niceIcon.translatesAutoresizingMaskIntoConstraints = false
        niceIcon.heightAnchor.constraint(equalToConstant: 100).isActive = true
        niceIcon.widthAnchor.constraint(equalToConstant: 100).isActive = true
        niceIcon.centerXAnchor.constraint(lessThanOrEqualTo: niceIcon.superview!.centerXAnchor).isActive = true
        niceIcon.centerYAnchor.constraint(lessThanOrEqualTo: niceIcon.superview!.centerYAnchor).isActive = true
    }
}
  1. example of storyboard, raw icon misplaced and without any constraints.

在此处输入图片说明

  1. on the simulator:

在此处输入图片说明


another solution (a bit more verbose) might be to add constraints, with the same constant, on leftAnchor , rightAnchor , bottomAnchor , topAnchor . Such constant stands for the distance between the superview and the subview itself.

You can use the following example code:-

Here I have given the width and height of View as (200,400) and for UIImageView I have given the size as (50,50)

let whitView = UIView(frame:CGRect(self.view.frame.size.width/2-200/2,self.view.frame.size.height/2-400/2,200,400))
whitView.backgroundcolor = UIColor.white
view.addSubview(whitView)
let imgView = UIImageView(frame:CGRect(whitView.frame.size.width/2-50/2,whitView.frame.size.height/2-50/2,50,50))
imgView.image = UIImage(named: "abc.png")
whitView.addSubview(imgView)

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