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?
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:
Now make all four margins flexible, and the view will stay where you put it in relation to any screen size.