简体   繁体   中英

Put a stack view at the center of the screen in IOS

I am new in iOS application development. In my application I need a login form at the centre of the screen. I put all the elements in a UIStackView and that looks fine, but this UIStackView not align centred in all screens. How to make this UIStackView at the centre of screens.

如下面的屏幕截图所示,添加对齐约束,它将所​​有设备的堆栈视图对齐到屏幕中心

you can use viewDidLoad() , and viewWillTransitionToSize() to programmatically center the view. So Long as you have an IBOutlet bound to the stack view (called stackView in this example), this should work

stackView.frame.origin.x = view.frame.width/2 - stackView.frame.width/2
stackView.frame.origin.y = view.frame.height/2 - stackView.frame.width/2

just add this code in viewDidLoad and viewWillTransitionToSize() , depending if your program allows rotation, viewWillTransitionToSize() is optional. If you do use viewWillTransitionToSize() , there should be a parameter for size that you can replace view.frame with.

viewDidLoad() is called on startup, and viewWillTransitionToSize() is called whenever the phone is rotated, if you want that functionality.

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