以纵向方式获取垂直堆栈视图以在横向中水平对齐的最佳方法是什么。我已经尝试过代码和自动布局解决方案但它们没有用。在故事板中有没有简单的方法呢?
答案 0 :(得分:4)
当轮换发生时,您需要以编程方式更新UIStackView
的 axis
属性。文件说:
确切的布局取决于堆栈视图的轴, 分布,对齐,间距和其他属性。
没有办法纯粹使用故事板来实现这一点。
我创建了一个演示项目并验证它是否有效。我由一个视图控制器组成。
class ViewController: UIViewController {
@IBOutlet weak var stackView: UIStackView!
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator:UIViewControllerTransitionCoordinator) {
coordinator.animateAlongsideTransition({ (context) -> Void in
let orientation = UIApplication.sharedApplication().statusBarOrientation
if orientation.isPortrait {
self.stackView.axis = .Horizontal
} else {
self.stackView.axis = .Vertical
}
}, completion: nil)
}
}
stackView
是在故事板中创建的UIStackView
,初始轴设置为“水平”。
答案 1 :(得分:3)
Swift 3.0
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animate(alongsideTransition: { (context) -> Void in
let orientation = UIApplication.shared.statusBarOrientation
if orientation.isPortrait {
self.stackView.axis = .horizontal
} else {
self.stackView.axis = .vertical
}
}, completion: nil)
}
答案 2 :(得分:2)
快捷键5
技巧是在“高度”紧凑时将StackView轴设置为“水平”。
查看此帖子:Magical View Rotation with StackView
我尝试过,在iOS 13 swift 5中效果很好
答案 3 :(得分:0)
这可以通过您的 ViewController
轻松完成:
class ViewController: UIViewController {
@IBOutlet weak var stackView: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
self.stackView.axis = self.view.bounds.width > self.view.bounds.height ? .horizontal : .vertical
}
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
self.stackView.axis = self.view.bounds.width > self.view.bounds.height ? .horizontal : .vertical
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
self.stackView.axis = self.view.bounds.width > self.view.bounds.height ? .horizontal : .vertical
}
}
注意:来自已接受答案的 statusBarOrientation
现在是一个已弃用的 API……这也是一种检查方向的间接方法,在某些情况下会失败。只需检查视图的宽度和高度 - 它完全在您的控制之下并且可靠。