presentViewControllerで呼び出すViewControllerの背景を透明にするには呼び出すViewControllerのmodalPresentationStyle
に.OverCurrentContext
をセットしてviewのbackgroundColorをclearColorにします。
class ViewController: UIViewController { override func viewDidAppear(animated: Bool) { view.backgroundColor = UIColor.greenColor() let vc = UIViewController() vc.modalPresentationStyle = .OverCurrentContext vc.view.backgroundColor = UIColor.clearColor() presentViewController(vc, animated: true, completion: nil) } }
注意点1
.OverCurrentContext
を使った場合、呼び出し元のviewWillDisappear
は呼ばれないので注意が必要です。
しかし呼び出される側のviewWillApeearは呼ばれます。
class ViewController: UIViewController { override func viewDidAppear(animated: Bool) { view.backgroundColor = UIColor.greenColor() let vc = UIViewController() vc.modalPresentationStyle = .OverCurrentContext vc.view.backgroundColor = UIColor.clearColor() presentViewController(vc, animated: true, completion: nil) } override func viewWillDisappear(animated: Bool) { print("viewWillDisappear") // これは呼ばれない } }
注意点2
presentされるViewControllerのinitializerでmodalPresentationStyleにOverCurrentContextをセットする事もできます。
しかしpresentされる側のviewDidLoadでmodalPresentationStyleに値を入れても反映されません。
理由はpresentViewControllerの前にmodalPresentationStyleの値がセットされている必要があるからです。
その為presentされる側で値をセットするならinitializerでセットする必要があります。
class ViewController: UIViewController { override func viewDidAppear(animated: Bool) { view.backgroundColor = UIColor.greenColor() presentViewController(ModalViewController(), animated: true, completion: nil) } } class ModalViewController: UIViewController { convenience init() { self.init(nibName: nil, bundle: nil) modalPresentationStyle = .OverCurrentContext } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override func viewDidLoad() { view.backgroundColor = UIColor.clearColor() } }