//
// ViewController.swift
// 456UI
//
// Created by 柏超曾 on 2018/2/13.
// Copyright © 2018年 柏超曾. All rights reserved.
//
import UIKit
class ViewController: UIViewController,GetMessageDelegate
{
var _button:UIButton?
var _label:UILabel?
override func viewDidLoad()
{
super.viewDidLoad()
self.title = "RootViewController"
//创建label 用来接收传过来的值
_label = UILabel(frame: CGRect(x: 50, y: 100, width: 220, height: 44))
_label?.text = "get message from next page"
_label?.textAlignment = NSTextAlignment.center
_label?.backgroundColor = UIColor.cyan
self.view.addSubview(_label!)
//创建button 点击跳转到下一个界面
_button = UIButton(frame:CGRect(x:60,y:200,width:200,height:44))
_button?.setTitle("go to next page", for: UIControlState.normal)
_button?.setTitleColor(UIColor.yellow, for: UIControlState.normal)
_button?.backgroundColor = UIColor.blue
_button?.addTarget(self, action: #selector(nextPage), for: UIControlEvents.touchUpInside)
self.view.addSubview(_button!)
}
//push
@objc func nextPage()
{
let nextVC = NextViewController()
//指定代理
nextVC.delegate = self
self.navigationController!.pushViewController(nextVC,animated:true)
}
//接收传过来的值
func getMessage(controller:NextViewController,string:String)
{
_label?.text = string
if(string == "")
{
_label?.text = "null"
}
}
}
//
// secondViewController.swift
// 456UI
//
// Created by 柏超曾 on 2018/2/13.
// Copyright © 2018年 柏超曾. All rights reserved.
//
import Foundation
import UIKit
//创建协议
protocol GetMessageDelegate:NSObjectProtocol
{
//回调方法 传一个String类型的值
func getMessage(controller:NextViewController,string:String)
}
class NextViewController: UIViewController
{
var delegate:GetMessageDelegate?
var _textField:UITextField?
override func viewDidLoad()
{
super.viewDidLoad()
self.title = "SecondViewController"
self.view.backgroundColor = UIColor.white
//创建textField 用来输入要传的值
_textField = UITextField(frame: CGRect(x: 60, y: 100, width: 200, height: 44))
_textField?.borderStyle = UITextBorderStyle.roundedRect
_textField?.placeholder = "input sth to send back"
self.view.addSubview(_textField!)
//创建返回的button
let myButton = UIButton(frame:CGRect(x:60,y:200,width:200,height:44))
myButton.center = CGPoint.init(x: 160, y: 200)
myButton.setTitle("send message back",for:.normal)
myButton.addTarget(self,action:#selector(goBack),for:.touchUpInside)
myButton.backgroundColor = UIColor.blue
self.view.addSubview(myButton)
}
@objc func goBack()
{
//调用代理方法
if((delegate) != nil)
{
delegate?.getMessage(controller: self,string:_textField!.text!)
self.navigationController?.popToRootViewController(animated: true)
}
}
}