今回はInterface BuilderのSegueは使用しない方法で実装します。
I introduce the method of changeover ViewController today.
I implement without Interface Builder's segue this time.
環境(Environment):Xcode 8,Swift 3
新しいViewControllerを起動するときにはpresentを使用します。
またViewControllerの出方をmodalTransitionStyleで指定します。
Use present when you launch new ViewController.
And specify style of starting ViewController using modalTransitionStyle.
newViewController.modalTransitionStyle = UIModalTransitionStyle.coverVertical
self.present(newViewController, animated: true, completion: nil)
新しく起動したViewControllerを閉じて、元のViewControllerに戻る場合は、delegateを使用して新しいViewControllerから元のViewControllerを呼び出し、元のViewControllerでdismissを使用します。
When you close new ViewController and back to base ViewController, call base ViewController from new ViewController using delegate, and use dismiss in base ViewController.
newViewController.dismiss(animated: true, completion: nil)
では全てのコードを見てみましょう。
Let's full text of code.
ViewController.swift
import UIKit
class ViewController: UIViewController,NewViewControllerDelegate {
let newViewController:NewViewController = NewViewController()
let buttonChange:UIButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
buttonChange.frame = CGRect(x:10,y:100,width:200,height:50)
buttonChange.setTitle("Change", for: .normal)
buttonChange.setTitleColor(UIColor.blue, for: .normal)
buttonChange.addTarget(self, action: #selector(self.touchUpButtonChange), for: .touchUpInside)
self.view.addSubview(buttonChange)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Tap Change Button
func touchUpButtonChange(){
newViewController.delegate = self
newViewController.modalTransitionStyle = UIModalTransitionStyle.coverVertical
self.present(newViewController, animated: true, completion: nil)
}
func backViewController(){
newViewController.dismiss(animated: true, completion: nil)
}
}
NewViewController.swift
import UIKit
@objc protocol NewViewControllerDelegate{
func backViewController()
}
class NewViewController:UIViewController{
weak var delegate:NewViewControllerDelegate?
let buttonBack:UIButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
buttonBack.frame = CGRect(x:10,y:100,width:200,height:50)
buttonBack.setTitle("Back", for: .normal)
buttonBack.setTitleColor(UIColor.blue, for: .normal)
buttonBack.addTarget(self, action: #selector(self.touchUpButtonBack), for: .touchUpInside)
self.view.addSubview(buttonBack)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Tap Back Button
func touchUpButtonBack(){
delegate?.backViewController()
}
}
にほんブログ村
クリエイティブライフ ブログランキングへ
0 件のコメント:
コメントを投稿