swift 5 autoresizingMask not working at all

1k views Asked by At

I'm familiar with Autolayout programmingly but I also want to try autoresizingMask programmingly. I have a green box created and want center it horizontally, but fixed distance for top and bottom, however whatever I tried any combination of autoresizingMask it never work.

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .white
    view.autoresizesSubviews = true
    view.translatesAutoresizingMaskIntoConstraints = true

    let myView = UIView(frame: CGRect(x: 175, y: 100, width: 30, height: 30))
    myView.backgroundColor = .green
    view.addSubview(myView)
    myView.autoresizingMask = [.flexibleRightMargin, .flexibleLeftMargin]
}

I tried it on iphone SE2 and iphone 11 Pro Max, the green block is centered on SE but never on Pro Max, anyone know what is going on?

2

There are 2 answers

0
matt On

What autoresizing does is to maintain the view according to its frame and the autoresizing mask. So the first step, if you want this view centered, is to center it:

myView.center = CGPoint(x:view.bounds.midX, y:view.bounds.midY)

Now make all four margins flexible, and the view will stay where you put it in relation to any screen size.

0
Blazej SLEBODA On

By default the view is rigid and has constant distance to the top left corner. You are looking for a flexibleWidth and Height

autoresizingMask = [.flexibleHeight, .flexibleWidth]