今回の内容
- 簡単なハーフモーダルを作成
コードと簡単解説
表示するViewを作成 (modalPresentationStyle = .customの場合)
-
modalPresentationStyle = .custom
で作成する場合、表示したViewを下にスワイプする事でViewを閉じる為にUISwipeGestureRecognizer
の.direction
を.down
で設定します。
import UIKit
class ModalView:UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
let downSwipeDetection = UISwipeGestureRecognizer(target: self, action: #selector(downScreenSwipe))
downSwipeDetection.direction = .down
view.addGestureRecognizer(downSwipeDetection)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
view.frame.origin.y = UIScreen.main.bounds.maxY / 2
view.frame.size.height = UIScreen.main.bounds.height / 2
view.layer.cornerRadius = 20.0
view.layer.maskedCorners = [.layerMinXMinYCorner,.layerMaxXMinYCorner]
view.backgroundColor = .systemGreen
}
@objc func downScreenSwipe(){
dismiss(animated: true, completion: nil)
}
}
表示するViewを作成 (modalPresentationStyle = .automaticの場合)
import UIKit
class ModalView:UIViewController{
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
view.frame.origin.y = UIScreen.main.bounds.maxY / 2
view.frame.size.height = UIScreen.main.bounds.height / 2
view.layer.cornerRadius = 20.0
view.layer.maskedCorners = [.layerMinXMinYCorner,.layerMaxXMinYCorner]
view.backgroundColor = .systemGreen
}
}
ViewController
-
.modalPresentationStyle = .automatic
は左側の画像の様になります。 -
.modalPresentationStyle = .custom
は右側の画像の様になります。
import UIKit
class ViewController: UIViewController {
let showModalViewButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
let showModalViewButton = UIButton()
showModalViewButton.frame = CGRect(x: view.frame.maxX / 4, y: 100, width: view.frame.width / 2, height: 40)
showModalViewButton.backgroundColor = .systemGreen
showModalViewButton.setTitle("showModalView", for: .normal)
showModalViewButton.titleLabel?.textColor = .black
showModalViewButton.addTarget(self, action: #selector(showView), for: .touchDown)
view.addSubview(showModalViewButton)
}
@objc func showView(){
let modalVC = ModalView()
modalVC.modalPresentationStyle = .custom //または.automaticなど
self.present(modalVC, animated: true, completion: nil)
}
}
終わり
ご指摘、ご質問などありましたら、コメントまでお願い致します。