storyboard에서 버튼을 생성하면 다른 뷰로 전환시 segment를 사용하여 쉽게 전환이 가능합니다.

동적으로 버튼을 생성했을 때에는 코드를 작성하여 화면 전환을 해야하는데 이때 아래의 코드를 사용합니다.

presentViewController 가 swift3에서 present 로 변경되었습니다. 


//버튼 생성시 이벤트를 주기위해 addTarget 사용

button.addTarget(ViewController(), action: #selector(ViewController.buttonPressed), for: .touchUpInside)


//버튼 생성시 설정해준 buttonPressed function에 tag별로 클릭 이벤트를 작성한다.

func buttonPressed(sender : UIButton) {

        print("\(sender.tag) 버튼 클릭됨")

        if sender.tag == 0 {

            let uvc = self.storyboard?.instantiateViewController(withIdentifier: "addClothesViewController")

            uvc?.modalTransitionStyle = UIModalTransitionStyle.flipHorizontal //페이지 전환시 에니메이션 효과 설정

            present(uvc!, animated: true, completion: nil)

        }else if sender.tag == 1 {

           .... 

        }

        

}


위의 코드에서 (withIdentifier: "addClothesViewController")

identifier는 스토리보드에서 전환할 화면의 storyboard 아이디로 설정한다.



새로 전환된 화면에서 본래의 화면으로 back할때에는 버튼을하나 만들어주고 버튼 액션에 아래와 같은 코드를 사용한다.


@IBAction func backToMainButton(_ sender: Any) {

        self.presentingViewController?.dismiss(animated: true, completion: nil)

}


+ Recent posts