I have totally different layouts for landscape and portrait.
In portrait the screen does not have the menu on left and in landscape the screen contains the menu on left side.
Is that possible to do so in iOS?
CodePudding user response:
You can do it programmatically, declare your button menu under your class controller like that:
let myButton: UIButton = {
let b = UIButton()
b.backgroundColor = .white
b.setTitle("Menu", for: .normal)
b.setTitleColor(.black, for: .normal)
b.titleLabel?.font = .systemFont(ofSize: 17, weight: .semibold)
b.layer.cornerRadius = 16
b.clipsToBounds = true
b.alpha = 0
b.isEnabled = false
b.translatesAutoresizingMaskIntoConstraints = false
return b
}()
Now in viewDidLoad set constraints and cal the detect func:
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .darkGray
view.addSubview(myButton)
myButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
myButton.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20).isActive = true
myButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
myButton.widthAnchor.constraint(equalToConstant: 120).isActive = true
detectRotation()
}
after that write the detect func (I add animation but you can't do it):
fileprivate func detectRotation() {
if UIDevice.current.orientation == UIDeviceOrientation.landscapeLeft {
print("landscape left")
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut, animations: {
self.myButton.alpha = 1
self.myButton.isEnabled = true
self.view.layoutIfNeeded()
}, completion: nil)
} else if UIDevice.current.orientation == UIDeviceOrientation.landscapeRight {
print("landscape right")
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut, animations: {
self.myButton.alpha = 1
self.myButton.isEnabled = true
self.view.layoutIfNeeded()
}, completion: nil)
} else {
print("porrait")
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut, animations: {
self.myButton.alpha = 0
self.myButton.isEnabled = false
self.view.layoutIfNeeded()
}, completion: nil)
}
override viewWillTransition func and cal detectRotation func:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
detectRotation()
}
This is the result:
portrait
Landscape
CodePudding user response:
You can use
yourMenuView.isHidden = UIDevice.current.orientation.isPortrait
like that
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
yourMenuView.isHidden = UIDevice.current.orientation.isPortrait
}