简体   繁体   English

将堆栈视图放在IOS屏幕的中央

[英]Put a stack view at the center of the screen in IOS

I am new in iOS application development. 我是iOS应用程序开发的新手。 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. 我将所有元素都放在UIStackView ,看起来不错,但是该UIStackView并非在所有屏幕中居中对齐。 How to make this UIStackView at the centre of screens. 如何使UIStackView处于屏幕中心。

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

you can use viewDidLoad() , and viewWillTransitionToSize() to programmatically center the view. 您可以使用viewDidLoad()viewWillTransitionToSize()以编程方式使视图居中。 So Long as you have an IBOutlet bound to the stack view (called stackView in this example), this should work 只要您将IBOutlet绑定到堆栈视图(在此示例中称为stackView),它就应该起作用

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. 只需将此代码添加到viewDidLoadviewWillTransitionToSize() ,这取决于您的程序是否允许旋转,因此viewWillTransitionToSize()是可选的。 If you do use viewWillTransitionToSize() , there should be a parameter for size that you can replace view.frame with. 如果您确实使用viewWillTransitionToSize() ,则应该有一个尺寸参数,您可以用它替换view.frame

viewDidLoad() is called on startup, and viewWillTransitionToSize() is called whenever the phone is rotated, if you want that functionality. 如果需要该功能,则在启动时调用viewDidLoad() ,并在每次旋转手机时调用viewWillTransitionToSize()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM