2016년 6월 22일 수요일

Custom Segue animation left to right, right to left @@ in Swift2.x - Xcode 7.3 iOS 9.3


페이지 이동 시 segue를 사용합니다. 기본적으로 포함된 Segue가 아닌Custom Segue 를 만들어 왼쪽에서 오른쪽, 오른쪽에서 왼쪽으로 나오는 효과를 만들도록 하겠습니다.

동영상을 먼저 보고 진행하겠습니다. 



일단 먼저 프로젝트를 생성 후 ViewController를 2개 추가! 총 3개가 되도록 합니다.



뷰를 구분하기 위해 각각 컬러를 넣고 버튼을 넣어줍니다.



추가된 2개의 ViewController 에 적용할 Swift 파일을 생성합니다. 





위 같은 방법으로 RightViewController ,LeftViewController, CustomSegueClass 파일을 생성합니다.
아래처럼 폴더구성이 되어 있어야 합니다.

이제 RightViewController, LeftViewController 에 클래스를 적용합니다

 - RightViewController -


- LeftViewController -



적용이 끝났다면 버튼에 ViewController 에 있는 Left 버튼과 Right 버튼에 Custom Segue
를 추가하여 뷰가 나타나는 효과부터 만들도록 하겠습니다. 

버튼을 우클릭 후 RightViewController 에 드래그 하면 Segue메뉴가 활성화 됩니다. 
"Custom"을 선택해 주세요


ViewController 와  RightViewController 사이에 이상한 화살표 줄이 생깁니다.
같은 방법으로 Left 버튼에도 Custom Segue를 추가합니다.


아래 이미지 처럼 되도록 ..


이제 여기서 코딩작업을 하겠습니다.
전에 만들어놓은  CustomSegueClass.swift 파일을 열어 아래코드를 넣습니다.


import UIKit

// LeftViewController  뷰 이동
class left: UIStoryboardSegue {
    override func perform()
    {
        //ViewContoroller
        let src = self.sourceViewController as UIViewController
        // LeftViewController
        let dst = self.destinationViewController as UIViewController
        src.view.superview?.insertSubview(dst.view, aboveSubview: src.view)
        // LeftViewController 초기 위치
        dst.view.transform = CGAffineTransformMakeTranslation(-src.view.frame.size.width, 0)
        //애니메이션 실행
        UIView.animateWithDuration(0.25,
                                   delay: 0.0,
                                   options: UIViewAnimationOptions.CurveEaseInOut,
                                   animations: {
                                    // 이동할 위치
                                    dst.view.transform = CGAffineTransformMakeTranslation(0, 0)
                                     // ViewController 이동할 위치
                                    src.view.transform = CGAffineTransformMakeTranslation(src.view.frame.size.width/3, 0)                       
            },
                                   completion: { finished in
                                    // 애니메이션 완료 후 실행
                                    src.presentViewController(dst, animated: false, completion: nil)
            }
        )
    }
}

// LeftViewController  뷰 닫기 
class Unwind_left: UIStoryboardSegue {
    override func perform()
    {   
         //ViewContoroller
        let src = self.sourceViewController as UIViewController
        //LeftViewController
        let dst = self.destinationViewController as UIViewController
        src.view.superview?.insertSubview(dst.view, belowSubview: src.view)
        // LeftViewController 초기 위치
        src.view.transform = CGAffineTransformMakeTranslation(0, 0)
         // ViewController 초기 위치
        dst.view.transform = CGAffineTransformMakeTranslation(src.view.frame.size.width/3, 0)
        UIView.animateWithDuration(0.25,
                                   delay: 0.0,
                                   options: UIViewAnimationOptions.CurveEaseInOut,
                                   animations: {
 // LeftViewController 이동할 위치
                                    src.view.transform = CGAffineTransformMakeTranslation(-src.view.frame.size.width, 0)
 // ViewController 이동할 위치
                                    dst.view.transform = CGAffineTransformMakeTranslation(0, 0)
            },
                                   completion: { finished in
                                    // 애니메이션 완료 후 LeftViewController 없애기
                                    src.dismissViewControllerAnimated(false, completion: nil)
            }
        )
    }
    
}

// RightViewController  뷰 이동
class right: UIStoryboardSegue {
    override func perform()
    {
        let src = self.sourceViewController as UIViewController
        let dst = self.destinationViewController as UIViewController
        src.view.superview?.insertSubview(dst.view, aboveSubview: src.view)
        dst.view.transform = CGAffineTransformMakeTranslation(src.view.frame.size.width, 0)
        UIView.animateWithDuration(0.25,
                                   delay: 0.0,
                                   options: UIViewAnimationOptions.CurveEaseInOut,
                                   animations: {
                                    dst.view.transform = CGAffineTransformMakeTranslation(0, 0)
                                    src.view.transform = CGAffineTransformMakeTranslation(-src.view.frame.size.width/3, 0)
            },
                                   completion: { finished in
                                    src.presentViewController(dst, animated: false, completion: nil)
            }
        )
    }
}


// RightViewController  뷰 닫기
class Unwind_right: UIStoryboardSegue {
    override func perform()
    {
        let src = self.sourceViewController as UIViewController
        let dst = self.destinationViewController as UIViewController
        src.view.superview?.insertSubview(dst.view, belowSubview: src.view)
        src.view.transform = CGAffineTransformMakeTranslation(0, 0)
        dst.view.transform = CGAffineTransformMakeTranslation(-src.view.frame.size.width/3, 0)
        UIView.animateWithDuration(0.25,
                                   delay: 0.0,
                                   options: UIViewAnimationOptions.CurveEaseInOut,
                                   animations: {
                                    src.view.transform = CGAffineTransformMakeTranslation(src.view.frame.size.width, 0)
                                    dst.view.transform = CGAffineTransformMakeTranslation(0, 0)
            },
                                   completion: { finished in
                                    src.dismissViewControllerAnimated(false, completion: nil)
            }
        )
    }
}



이제 이 클래스 값들을 적용해보자
Right 버튼과 RightViewController 사이에있는  segue를 선택하면 우측 메뉴가뜬다



Identifier =  "rightsegue" 입력하고  Class = Right 를 선택 합니다. (Right 는  CustomSegueClass.swift 파일에 만든 클래스중  RightViewController를 이동시켜주는 클래스 값이다)


같은 방법으로 left버튼과 LeftViewController 사이 segue 에도
Identifier =  "leftsegue" 입력하고  Class = left 를 선택 합니다.

여기까지 진행하셨다면 시뮬레이션 으로 앱을 실행해보세요 버튼 클릭시 View 가 이동하는것을 확인
할 수 있습니다. 이제 BACK 버튼 기능을 넣어보자

ViewController.swift 파일을 열어 코딩을 추가해준다 (이미지 참조)

- 추가해 줄 코딩 -
 @IBAction func returnFromSegueActions(segue:UIStoryboardSegue){
        
    }



다시 Main.storyboard 로 돌아와
RightViewController 에 있는 BACK 버튼을  까지 드래그 한다
코딩이 제대로 되었다면 returnFromSegueActions: 이 뜨는것을 확인 할 수 있다. 선택해준다.




LeftViewController 에 있는 BACK 버튼도 동일하게 진행한다



아래 이미지처럼 RightViewController와 LeftViewController 에  Unwind segue to"Exit" 가 추가되었을 것이다.


RightViewController 에 있는 Unwind segue to"Exit" 를 선택하면 우측에 메뉴가 뜬다




Identifier =  "rightUnwindsegue" 입력하고  Class = Unwind_Right 를 선택 합니다.



같은방법으로 LeftViewController 에 있는 Unwind segue to"Exit" 를 선택하면 우측에 메뉴가 뜨면
Identifier =  "leftUnwindsegue" 입력하고  Class = Unwind_Left 를 선택 합니다.



이제 시뮬레이터로 앱을 실행하여 버튼을 눌러보세요 처음에 첨부했던 영상처럼 되는것을 확인 하실 수 있을겁니다.

참고!!

LeftViewController or RightViewController 에 있는 Unwind segue to"Exit" 를 선택하여 Identifier =  "leftUnwindsegue" 입력하고 클래스를 선택하지 않고 코딩으로 처리 하는 방법입니다.
ViewController.swift에 아래 코딩을 추가해줍니다.


 override func segueForUnwindingToViewController(toViewController: UIViewController, fromViewController: UIViewController, identifier: String?) -> UIStoryboardSegue {
        if let id = identifier{
            if id == "rightsegue" {
                let unwindSegue = Unwind_right(identifier: id, source: fromViewController, destination: toViewController, performHandler: { () -> Void in
                    
                })
                return unwindSegue
            }
            
            if id == "leftsegue" {
                let unwindSegue = Unwind_left(identifier: id, source: fromViewController, destination: toViewController, performHandler: { () -> Void in
                    
                })
                return unwindSegue
            }
            
        }
        return UIStoryboardSegue(identifier: identifier, source: fromViewController, destination: toViewController)
    }









댓글 6개:

  1. 많이 부족한 자료입니다. 도움이 되셨으면 좋겠습니다.

    답글삭제
  2. 안녕하세요
    혹시 위에서 아래로 내려오게 할려면 어떻게 해야 하는지요?
    CGAffineTransform 의 x y 를 변경해서 오른쪽이나 왼쪽에서 부터 시작을 합니다.
    할려고 하는것은 위에서 아래로 화면에 반만 채울려고 합니다.

    답글삭제
  3. 드래그 기능을 막아두신 이유라도 있는지요??.. ㅜㅜ

    답글삭제
    답글
    1. 팁으로 드래그 방지와 우클릭 방지하는 포스트를 올리는 중에 적용했던 설정들이 그대로 있었네요 다시 풀었습니다.

      삭제
  4. 좋은 정보감사합니다
    쉽게 배웠습니다.

    답글삭제

추천 게시물

애플 개발자 등록방법 2016년 5월 8일 기준!!

애플 개발자 등록 절차 1. 개발자 등록 페이지 이동    애플 개발자 로그인 > Account 페이지 이동 > 하단 영역 클릭 (이미지 참조)   >> Enroll 클릭 >> 무조건 승인!! ...