use tag to combine #objc func methods - swift

My code declares 2 different #objc func methods using UIPan gestureRecongnizzer. I would think there would be a way to use just 1 objc func method using a tag. All the function currently does is move the imageview around. I dont know if tag is the best way and I am open to other solutions I just want 1 func. Specifically look at pgGestureMethod and sgGestureMethod.
var pg = UIImageView()
var pgGesture = UIPanGestureRecognizer()
var pgCon = [NSLayoutConstraint]()
var sg = UIImageView()
var sgGesture = UIPanGestureRecognizer()
var sgCon = [NSLayoutConstraint]()
override func viewDidLoad() {
super.viewDidLoad()
[pg,sg].forEach({
$0.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview($0)
$0.isUserInteractionEnabled = true
})
pgGesture = UIPanGestureRecognizer(target: self, action: #selector(ViewController.pgGestureMethod(_:)))
pg.addGestureRecognizer(pgGesture)
sgGesture = UIPanGestureRecognizer(target: self, action: #selector(ViewController.sgGestureMethod(_:)))
sg.addGestureRecognizer(sgGesture)
}
#objc func pgGestureMethod(_ sender: UIPanGestureRecognizer){
self.view.bringSubviewToFront(pg)
let tranistioon = sender.translation(in: self.view)
pg.center = CGPoint(x: pg.center.x + tranistioon.x, y: pg.center.y + tranistioon.y)
sender.setTranslation(CGPoint.zero,in: self.view)
}
#objc func sgGestureMethod(_ sender: UIPanGestureRecognizer){
let tranistioon = sender.translation(in: self.view)
sg.center = CGPoint(x: sg.center.x + tranistioon.x, y: sg.center.y + tranistioon.y)
sender.setTranslation(CGPoint.zero,in: self.view)
}

Gesture recognisers have a view property that refers to the view to which they are added, so you don't even need a tag!
Just use one single action method like this:
#objc func pgGestureMethod(_ sender: UIPanGestureRecognizer){
// I replaced every "pg" with "sender.view!"
self.view.bringSubviewToFront(sender.view!)
let tranistioon = sender.translation(in: self.view)
sender.view!.center = CGPoint(x: sender.view!.center.x + tranistioon.x, y: sender.view!.center.y + tranistioon.y)
sender.setTranslation(CGPoint.zero,in: self.view)
}
If not writing self.view.bringSubviewToFront(sg) is actually intentional, you can simply check sender.view!:
#objc func pgGestureMethod(_ sender: UIPanGestureRecognizer){
if sender.view == pg {
self.view.bringSubviewToFront(pg)
}
let tranistioon = sender.translation(in: self.view)
sender.view!.center = CGPoint(x: sender.view!.center.x + tranistioon.x, y: sender.view!.center.y + tranistioon.y)
sender.setTranslation(CGPoint.zero,in: self.view)
}

welcome to the Stackoverflow.
So in your case, you can understand which gesture was called from parameter in gesture function.
class SomeViewController: UIViewController {
var pg = UIImageView()
var pgGesture = UIPanGestureRecognizer()
var pgCon = [NSLayoutConstraint]()
var sg = UIImageView()
var sgGesture = UIPanGestureRecognizer()
var sgCon = [NSLayoutConstraint]()
override func viewDidLoad() {
super.viewDidLoad()
[pg,sg].forEach {[unowned self] in
$0.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview($0)
$0.isUserInteractionEnabled = true
}
pgGesture = UIPanGestureRecognizer(target: self, action: #selector(gestureDidRecognize(_:)))
pg.addGestureRecognizer(pgGesture)
sgGesture = UIPanGestureRecognizer(target: self, action: #selector(gestureDidRecognize(_:)))
sg.addGestureRecognizer(sgGesture)
}
}
#objc private extension SomeViewController {
func gestureDidRecognize(_ gesture: UIPanGestureRecognizer){
guard let gestureView = gesture.view else { return }
let transition = gesture.translation(in: view)
switch gesture {
case pgGesture:
view.bringSubviewToFront(pg)
default: break
}
gestureView.center = CGPoint(
x: gestureView.center.x + transition.x,
y: gestureView.center.y + transition.y)
gesture.setTranslation(.zero, in: view)
}
}

Related

can not call selector and gesture delegate iOS 13.2

my code works in iOS 12 last version but after iOS 13 this code can't call the selector
I used UIGestureRecognizerDelegate for iOS 13
here is my code
let panGest = UIPanGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
panGest.delegate = self
txtVw.addGestureRecognizer(panGest)
here is my let txtVw = subVws as! UITextView , txtVw = subVws as! UITextView
I used this code:
let panGest = UIPanGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
self.view.addGestureRecognizer(panGest)
its work but I have one subview and for subview isn't work & call !!
isn't call self.handleTap or gestureRecognizer(_:shouldRecognizeSimultaneouslyWith:)
Is this what you want?
class ViewController: UIViewController, UIGestureRecognizerDelegate {
#IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
let gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
gestureRecognizer.delegate = self
textView.addGestureRecognizer(gestureRecognizer)
textView.isUserInteractionEnabled = true
textView.isMultipleTouchEnabled = true
}
#objc func handlePan(_ gestureRecognizer: UIPanGestureRecognizer) {
if gestureRecognizer.state == .began || gestureRecognizer.state == .changed {
let translation = gestureRecognizer.translation(in: self.view)
//make sure the view is not nil
gestureRecognizer.view!.center = CGPoint(x: gestureRecognizer.view!.center.x + translation.x, y: gestureRecognizer.view!.center.y + translation.y)
gestureRecognizer.setTranslation(CGPoint.zero, in: self.view)
}
}
}

UIImageView transform loses swipe gesture

I have an image that I want to rotate every time the user swipes on it. It works the first time, and first time only! How is it that the view is losing the swipe gesture recognizer?
myCircle = UIImageView( ... )
myCircle.isUserInteractionEnabled = true
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(swiping(sender:)))
swipeLeft.direction = .left
myCircle.addGestureRecognizer(swipeLeft)
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(swiping(sender:)))
swipeRight.direction = .right
myCircle.addGestureRecognizer(swipeRight)
}
#objc func swiping(sender: UISwipeGestureRecognizer) {
// this function only called the first time!
if sender.direction == UISwipeGestureRecognizer.Direction.left {
myCircleRotation -= CGFloat(Double.pi/2)
} else if sender.direction == UISwipeGestureRecognizer.Direction.right {
myCircleRotation += CGFloat(Double.pi/2)
}
// if I comment out this next line, function is called (correctly) every swipe!
myCircle.transform = CGAffineTransform(rotationAngle: myCircleRotation)
}
You can add a UIView as a container view to your hierarchy, and then add the UIGestureRecognizers to the container view instead of to the UIImageView. This would allow your image to be rotated without impact to the gestures.
import UIKit
class ImageViewController: UIViewController {
#IBOutlet weak var myCircleView: UIImageView!
#IBOutlet weak var containerView: UIView!
var myCircleRotation:CGFloat = 0
override func viewDidLoad() {
super.viewDidLoad()
setupImage()
}
private func setupImage() {
let image = UIImage(named: "your-image")
myCircleView.image = image
myCircleView.isUserInteractionEnabled = true
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(swiping(sender:)))
swipeLeft.direction = .left
containerView.addGestureRecognizer(swipeLeft)
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(swiping(sender:)))
swipeRight.direction = .right
containerView.addGestureRecognizer(swipeRight)
}
#objc func swiping(sender: UISwipeGestureRecognizer) {
// this function only called the first time!
if sender.direction == UISwipeGestureRecognizer.Direction.left {
myCircleRotation -= CGFloat(Double.pi/2)
} else if sender.direction == UISwipeGestureRecognizer.Direction.right {
myCircleRotation += CGFloat(Double.pi/2)
}
UIView.animate(withDuration: 0.5) {
self.myCircleView.transform = CGAffineTransform(rotationAngle: self.myCircleRotation)
}
}
}

Swift Scroll to UITextField via UiscrollView only acts first time bug

im posting my full code here. the problem is when initially loading the app and the viewcontroller. it fully works. tap on the two textfields and the scrollview pushes up and keyboard is below the current textfield. but then if tapping out of the text field.. moving the the view up and retaping on the textfield it doesnt do it anymore. Also, if going back via nav controller and then loading again this viewcontroller, it wont do anything. it doesnt scroll anymore..( doesnt push the textfield up and keyboard goes below it anymore ) ...
import UIKit
import Parse
import Alamofire
import SwiftyJSON
class VCreservacion: UIViewController,UITextFieldDelegate,UIScrollViewDelegate {
var SUCURSALID = 0
var EMP_NOMBRE = ""
var DIRECCION = ""
var PROVINCIA = ""
var RESTID = 20556
#IBOutlet var lbl_empresa: UILabel!
#IBOutlet var lbl_direccion: UILabel!
#IBOutlet var lbl_step: UILabel!
#IBOutlet var cantidadView: UIView!
#IBOutlet var datePicker: UIDatePicker!
#IBOutlet var btn_reservar: UIButton!
#IBOutlet var stackView: UIStackView!
#IBOutlet var scrollView: UIScrollView!
#IBOutlet var txtComentario: UITextField!
#IBOutlet weak var txtCelular: UITextField!
var activeField: UITextField?
var steps = 2
// MARK: RESERVE ACTION
#IBAction func ReserveAction(_ sender: UIButton) {
print("Reservando...")
// For date formater
var dateformated = ""
var dateformated2 = ""
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
//formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) as TimeZone!
dateformated = formatter.string(from: datePicker.clampedDate)
dateformated2 = formatter.string(from: datePicker.date)
print(dateformated)
print(dateformated2)
let cart = Cart.sharedInstance
guard let user = PFUser.current() else {
cart.showAlertView("Login", message: "Debes estar logeado para poder reservar.")
return
}
Alamofire.request("URL String", parameters: ["qty": "\(steps)","sucursalid":"\(self.SUCURSALID)","restid":"\(RESTID)","comment":"\(txtComentario.text!)","phone":"\(txtCelular.text!)","datetime":"\(dateformated)","action":"request","userid":"\(user.objectId!)"]).authenticate(usingCredential: cart.credential).responseJSON() {
response in
if (response.error != nil ) {
print(response.error.debugDescription)
print(response.request)
cart.showAlertView("Error", message: "there was an error.")
}
if(response.result.value != nil) {
let json = JSON(response.result.value!);
print(json);
let success:Bool = json["success"].boolValue
let error: Bool = json["error"].boolValue
if(success) {
print("con exito")
let alert = UIAlertController(title: "Reserva Enviada", message: "Tu reserva ha sido enviada y serĂ¡ revisada por el establecimiento", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
UIAlertAction in
// Get the previous Controller.
let targetController: UIViewController = (self.navigationController?.viewControllers[self.navigationController!.viewControllers.count - 3])!
// And go to that Controller
self.navigationController?.popToViewController(targetController, animated: true)
}
alert.addAction(okAction)
self.present(alert,animated:true)
}
}
}
}
#IBAction func stepperValue(_ sender: UIStepper) {
self.lbl_step.text = Int(sender.value).description
steps = Int(sender.value)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
registerForKeyboardNotifications()
self.scrollView.delegate = self
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
deregisterFromKeyboardNotifications()
self.scrollView.delegate = nil
}
// MARK: Viewdidload
override func viewDidLoad() {
super.viewDidLoad()
// enable scroll on scrollview
self.scrollView.isScrollEnabled = true
// step label initial value 2
self.lbl_step.text = "2"
// Get celular or phone
if ( Cart.sharedInstance.User_celular != "") {
txtCelular.text = Cart.sharedInstance.User_celular
} else {
txtCelular.text = Cart.sharedInstance.User_phone
}
let nearesthour = Date().nearestHour()
self.datePicker.minimumDate = nearesthour
self.txtComentario.delegate = self
self.txtCelular.delegate = self
self.txtCelular.tag = 20
self.scrollView.delegate = self
// tap gesture recognizer
let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
self.scrollView.addGestureRecognizer(tap)
print("el enarest hour es \(nearesthour as Date?) y el date normal es \(Date())")
self.btn_reservar.layer.cornerRadius = 10
self.cantidadView.layer.cornerRadius = 10
self.lbl_empresa.text = EMP_NOMBRE
self.lbl_direccion.text = DIRECCION
/*
print("VC Reservacion")
print("SUCURSAL \(SUCURSALID) ")
print("EMP NOMBRE " + EMP_NOMBRE)
print("DIRECCION " + DIRECCION)
*/
}
// MARK: TEXTFIELD STUFF
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
self.activeField = textField
return true
}
/*
func textFieldDidBeginEditing(_ textField: UITextField) {
self.activeField = textField
}
*/
func textFieldDidEndEditing(_ textField: UITextField) {
activeField = nil
}
func registerForKeyboardNotifications(){
//Adding notifies on keyboard appearing
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func deregisterFromKeyboardNotifications(){
//Removing notifies on keyboard appearing
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
#objc func keyboardWasShown(notification: NSNotification){
//Need to calculate keyboard exact size due to Apple suggestions
print(" Keyboaard shown")
var info = notification.userInfo!
let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
print(" el keyboardsize is \(keyboardSize)")
let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height + 80, 0.0)
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
var aRect : CGRect = self.view.frame
print("VIEW COMPLETE FRAME IS \(aRect)")
print("KEYBOARD FRAME HEIGHT \(keyboardSize!.height)")
aRect.size.height -= keyboardSize!.height
print("FRAME MENOS KEYBOARD ES \(aRect)")
print("SCROLLVIEW CONTENT \(self.scrollView.contentSize)")
if let activeField = self.activeField {
print("ACTIVEFIELD FRAME ORIGIN \(activeField.frame.origin) ")
print("Active field is textfield tag is \(activeField.tag)")
// if (!aRect.contains(activeField.frame.origin)){
print("arect Does Not contains activeField")
self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
print("TEXTFIELD FRAME ES \(activeField.frame)")
print(" SCROLLVIEW CONTENT \(self.scrollView.contentSize)")
//}
}
}
#objc func keyboardWillBeHidden(notification: NSNotification){
//Once keyboard disappears, restore original positions
var info = notification.userInfo!
let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
self.activeField = nil
self.view.endEditing(true)
self.scrollView.isScrollEnabled = false
}
#objc func handleTap(_ sender: UITapGestureRecognizer) {
self.view.endEditing(true)
print("Tap")
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.contentSize = CGSize(width: view.frame.width, height: view.frame.height)
print(" SCROLLVIEW CONTENT AFTER SUBVIEWS \(self.scrollView.contentSize)")
}
/* // NOT WORKING BECAUSE OF UISCROLLVIEW IN PLACE, MUST USE UITAPGESTURE RECOGNIZER
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
self.activeField?.resignFirstResponder()
}
*/
}
I had the same problem. Apparently there is a change in getting the size of the keyboard. I changed UIKeyboardFrameBeginUserInfoKey to UIKeyboardFrameEndUserInfoKey and got it to work again.
Here is my exact code for moving the view when the textfield is pressed
#objc func keyboardWasShown(notification: NSNotification){
self.scrollView.isScrollEnabled = true
var info = notification.userInfo!
let keyboardSize = (info[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size
let contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
var aRect : CGRect = self.view.frame
guard let kbHeight = keyboardSize?.height else{return}
aRect.size.height -= kbHeight
if let activeField = self.activeTextField {
if (!aRect.contains(activeField.frame.origin)){
self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
}
}
}

How to pass images to a NewViewController from ScrollView with Page Control in Swift

I am trying to make the images clickable and pass them to a new view controller with more details. I am using UIScrollView with UIPageController inside my HomeViewController.
I was trying to research but couldn't find any specific examples. I am thinking maybe pass it with segue but I can't figure out how. Any ideas are welcome. Thanks in advance. This is my code:
class HomeViewController: UIViewController, UIScrollViewDelegate {
#IBOutlet var pageControl: UIPageControl!
#IBOutlet var topScrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
pageScrollView()
}
func pageScrollView() {
self.topScrollView.isUserInteractionEnabled = true
self.topScrollView.addGestureRecognizer(UITapGestureRecognizer())
self.topScrollView.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: 200)
let scrollViewWidth:CGFloat = self.topScrollView.frame.width
let scrollViewHeight:CGFloat = self.topScrollView.frame.height
let imgOne = UIImageView(frame: CGRect(x:0, y:0,width:scrollViewWidth, height:scrollViewHeight))
imgOne.image = UIImage(named: "img1")
let imgTwo = UIImageView(frame: CGRect(x:scrollViewWidth, y:0,width:scrollViewWidth, height:scrollViewHeight))
imgTwo.image = UIImage(named: "img2")
let imgThree = UIImageView(frame: CGRect(x:scrollViewWidth*2, y:0,width:scrollViewWidth, height:scrollViewHeight))
imgThree.image = UIImage(named: "img3")
let imgFour = UIImageView(frame: CGRect(x:scrollViewWidth*3, y:0,width:scrollViewWidth, height:scrollViewHeight))
imgFour.image = UIImage(named: "img4")
let imgFive = UIImageView(frame: CGRect(x:scrollViewWidth*4, y:0,width:scrollViewWidth, height:scrollViewHeight))
imgFive.image = UIImage(named: "img5")
self.topScrollView.addSubview(imgOne)
self.topScrollView.addSubview(imgTwo)
self.topScrollView.addSubview(imgThree)
self.topScrollView.addSubview(imgFour)
self.topScrollView.addSubview(imgFive)
self.topScrollView.contentSize = CGSize(width:self.topScrollView.frame.width * 5, height:self.topScrollView.frame.height)
self.pageControl.currentPage = 0
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageWidth:CGFloat = scrollView.frame.width
let currentPage:CGFloat = floor((scrollView.contentOffset.x-pageWidth/2)/pageWidth)+1
// Change the indicator
self.pageControl.currentPage = Int(currentPage)
}
}
I figure it out. Hope it helps someone else. I added:
#objc var imgOne = UIImageView()
#objc var imgTwo = UIImageView()
#objc var imgThree = UIImageView()
#objc var imgFour = UIImageView()
#objc var imgFive = UIImageView()
#objc func imageTapped(_sender:UITapGestureRecognizer) {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "DetailsMapsViewController") as! DetailsMapsViewController
vc.restaurantMaps = self.restaurantArray[_sender.view!.tag]
self.navigationController?.pushViewController(vc, animated: true)
}
imgOne.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(HomeViewController.imageTapped)))
imgTwo.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(HomeViewController.imageTapped)))
imgThree.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(HomeViewController.imageTapped)))
imgFour.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(HomeViewController.imageTapped)))
imgFive.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(HomeViewController.imageTapped)))
imgOne.tag = 0
imgTwo.tag = 1
imgThree.tag = 2
imgFour.tag = 3
imgFive.tag = 4

UIVisualEffectView creating unwanted shadow while presenting new view

In my custom presentation transition I've created a new view controller which will pre presented on top of the current active view controller (see screenshot). Somehow there's a shadow behind the blue view controller and I have no idea where it's coming from. Is there a way to stop getting that shadow?
The project is completely empty and has only 2 empty view controllers.
This is the code I'm using:
class ViewController: UIViewController {
let transitionDelegate = TransitionManager()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .yellowColor()
let button = UIButton(type: .System)
button.frame = CGRectMake(10, 10, 50, 50)
button.addTarget(self, action: "test:", forControlEvents: .TouchUpInside)
button.backgroundColor = UIColor.redColor()
view.addSubview(button)
}
func test(sender: UIButton) {
let destination = UIViewController()
destination.view.backgroundColor = .blueColor()
destination.transitioningDelegate = transitionDelegate
destination.modalPresentationStyle = .Custom
presentViewController(destination, animated: true, completion: nil)
}
}
The code for presenting the view:
class PresentingTransition: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.3
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let presented = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!
let container = transitionContext.containerView()!
let durations = transitionDuration(transitionContext)
presented.view.alpha = 0
container.addSubview(presented.view)
UIView.animateWithDuration(durations, animations: { presented.view.alpha = 1 }) { transitionContext.completeTransition($0) }
}
}
The code for handling the presenting view controller:
class PresentationController: UIPresentationController {
var background: UIView!
override init(presentedViewController: UIViewController, presentingViewController: UIViewController) {
super.init(presentedViewController: presentedViewController, presentingViewController: presentingViewController)
prepareBackground()
}
func prepareBackground() {
self.background = UIView(frame: presentingViewController.view.bounds)
let blur = UIVisualEffectView(effect: UIBlurEffect(style: .Light))
blur.frame = background.bounds
blur.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
background.addSubview(blur)
let tapRecognizer = UITapGestureRecognizer(target: self, action: "backgroundTapped:")
background.addGestureRecognizer(tapRecognizer)
}
func backgroundTapped(tapRecognizer: UITapGestureRecognizer) {
presentingViewController.dismissViewControllerAnimated(true, completion: nil)
}
override func presentationTransitionWillBegin() {
let container = containerView!
background.frame = container.bounds
background.alpha = 0.0
container.insertSubview(background, atIndex: 0)
presentedViewController.transitionCoordinator()?.animateAlongsideTransition({ _ in self.background.alpha = 1.0 }, completion: nil)
}
override func dismissalTransitionWillBegin() {
presentedViewController.transitionCoordinator()?.animateAlongsideTransition({ _ in self.background.alpha = 0.0 }, completion: nil)
}
override func frameOfPresentedViewInContainerView() -> CGRect {
return containerView!.bounds.insetBy(dx: 100, dy: 100)
}
override func containerViewWillLayoutSubviews() {
background.frame = containerView!.bounds
presentedView()!.frame = frameOfPresentedViewInContainerView()
}
}