当屏幕方向改变时,我需要使我的收藏视图布局无效。由于iPhone X和其他产品具有安全区域插图;我需要根据屏幕安全区域插图定位单元格的子视图。
如果您从纵向在左右风景之间切换,则没有问题。但是,如果您从颠倒过来切换,我将无法捕捉方向变化,并且无法自动
我尝试了两种现有方法。
首先使用//Service
userRegistration(model): Observable<any>{
return this.http.post(url, model, httpOptions);
}
//Component
saveUser(model){
this.myService.userRegistration(model).subscribe(
data => {
//do something
},
error => {
//show message
}
);
}
。第二个是重写NotificationCenter
函数。都一样。
在CollectionViewController中:
viewWillTransitionToSize:withTransitionCoordinator:
在单元格中
NotificationCenter.default.addObserver(forName: UIDevice.orientationDidChangeNotification, object: nil, queue: nil) { (notif) in
self.collectionViewLayout.invalidateLayout()
}
从倒置切换到倒置时,不会调用 override func layoutSubviews() {
super.layoutSubviews()
let orientation = UIDevice.current.orientation
if let insets = UIApplication.shared.keyWindow?.safeAreaInsets {
if orientation == .landscapeLeft {
titleLabelLeadingConstraint.constant = insets.left + 20
titleLabelTrailingConstraint.constant = 20
} else if orientation == .landscapeRight {
titleLabelLeadingConstraint.constant = 20
titleLabelTrailingConstraint.constant = insets.right + 20
} else {
titleLabelLeadingConstraint.constant = 20
titleLabelTrailingConstraint.constant = 20
}
}
print("orin: \(orientation.rawValue) | left: \(titleLabelLeadingConstraint.constant) | right: \(titleLabelTrailingConstraint.constant)")
}
函数。但是正在调用print()
的{{1}}函数。
答案 0 :(得分:0)
您已经尝试过,可以使用viewWillTransitionToSize:withTransitionCoordinator:
检测方向变化。
我不知道您的第一次尝试,但是,请尝试以下操作:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
//If you need to invalidate your collectionView layout, do it in this function
super.viewWillTransition(to: size, with: coordinator)
if UIDevice.current.orientation.isLandscape {
//
} else {
//
}
}
如果您需要了解landscapeLeft或Right的区别,请按以下方式尝试代码:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
//If you need to invalidate your collectionView layout, do it in this function
super.viewWillTransition(to: size, with: coordinator)
if let insets = UIApplication.shared.keyWindow?.safeAreaInsets {
if UIDevice.current.orientation == .landscapeLeft {
titleLabelLeadingConstraint.constant = insets.left + 20
titleLabelTrailingConstraint.constant = 20
} else if UIDevice.current.orientation == .landscapeRight {
titleLabelLeadingConstraint.constant = 20
titleLabelTrailingConstraint.constant = insets.right + 20
} else {
titleLabelLeadingConstraint.constant = 20
titleLabelTrailingConstraint.constant = 20
}
}
}
注意: 您不需要注册观察员
答案 1 :(得分:0)
好。最后,我想到了不想做的事情。观察到的方向从细胞本身发生变化。
override func awakeFromNib() {
super.awakeFromNib()
NotificationCenter.default.addObserver(forName: UIDevice.orientationDidChangeNotification, object: nil, queue: nil) { (notif ) in
// doing my things already stated in the question's itself.
}
}
现在他们可以观察所有变化。但是我不知道这么多的登记是否明智。即使集合视图可以重复使用单元格,并且在我的情况下,最多也可以在屏幕上显示7至8个单元格。