我对大标题有一个奇怪的问题,当我将设备从横向旋转到纵向时,标题未对齐。您可能会看到随附的gif:
我不太确定是否归因于自定义BarButtonItem,但是在滚动之后,标题会重新调整为原始位置。
我的代码如下:
lazy var profileImageButton: UIButton = {
let b = UIButton(type: .system)
b.addTarget(self, action: #selector(openSideMenu), for: .touchUpInside)
b.setImage(UIImage(named: "testImage")?.withRenderingMode(.alwaysOriginal), for: .normal)
b.imageView?.contentMode = .scaleAspectFill
b.imageView?.clipsToBounds = true
b.translatesAutoresizingMaskIntoConstraints = false
return b
}()
var compactConstraints: [NSLayoutConstraint] = []
var regularConstraints: [NSLayoutConstraint] = []
var heightContraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
func setupUI() {
navigationItem.title = "Overview"
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: profileImageButton)
navigationController?.navigationBar.prefersLargeTitles = true
setupProfileImageButtonConstraints()
}
func setupProfileImageButtonConstraints() {
heightContraint = profileImageButton.heightAnchor.constraint(equalToConstant: 36)
heightContraint.priority = UILayoutPriority(999)
compactConstraints = [
profileImageButton.widthAnchor.constraint(equalToConstant: 20),
profileImageButton.heightAnchor.constraint(equalToConstant: 20)]
regularConstraints = [
profileImageButton.widthAnchor.constraint(equalToConstant: 36),
heightContraint
]
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
if traitCollection.verticalSizeClass == .compact {
NSLayoutConstraint.deactivate(regularConstraints)
NSLayoutConstraint.activate(compactConstraints)
profileImageButton.imageView?.layer.cornerRadius = 10
} else if traitCollection.verticalSizeClass == .regular {
NSLayoutConstraint.deactivate(compactConstraints)
NSLayoutConstraint.activate(regularConstraints)
profileImageButton.imageView?.layer.cornerRadius = 18
}
}
有什么办法可以避免这种失准吗?
编辑:
在我的tabBarController
中尝试将以下代码共享:
override var shouldAutorotate: Bool {
if let viewController = self.viewControllers?[self.selectedIndex] {
return viewController.shouldAutorotate
}
return super.shouldAutorotate
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if let viewController = self.viewControllers?[self.selectedIndex] {
return viewController.supportedInterfaceOrientations
}
return super.supportedInterfaceOrientations
}
override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
if let viewController = self.viewControllers?[self.selectedIndex] {
return viewController.preferredInterfaceOrientationForPresentation
}
return super.preferredInterfaceOrientationForPresentation
}
到目前为止的结果:
如您所见,旋转旋转为regularTitle
。可以像largeTitle
一样旋转回来吗?