首先创建两个控制器每个控制器上各有一个button
其次再第二个控制器中声明delegate
@objcprotocol ViewcontrollerDelegate: NSObjectProtocol{
@objc optionalfunc mainFun(string: NSString)
在第二个控制器中}
var delegate :TwoDelegate?
第二个控制器的代码如下import UIKit
@objcprotocol TwoDelegate:NSObjectProtocol{
func getmessage(string:NSString)
}
class TwoViewController:UIViewController,ViewcontrollerDelegate {
var delegate : TwoDelegate?
@IBAction func buttonclick(_ sender:UIButton) {
delegate?.getmessage(string:"789")
// dismiss(animated: true, completion: nil)
self.navigationController?.popViewController(animated:true)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
delegate?.getmessage(string:"caosiyuan")
let button = UIButton(frame:CGRect(x: 300, y:300, width: 100, height:100))
button.addTarget(self, action:#selector(back), for: .touchUpInside)
button.setTitle("fanhui", for: .normal)
view.addSubview(button)
}
func back() {
delegate?.getmessage(string:"numhbbi")
self.navigationController?.popViewController(animated:true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
第一个控制器代码如下
//
// ViewController.swift
// delegateProtocol
//
// Created by iApps on 17/2/15.
// Copyright © 2017年 iApps. All rights reserved.
//
import UIKit
@objc protocol ViewcontrollerDelegate:NSObjectProtocol{
@objcoptional func mainFun(string:NSString)
}
class TestClass {
weakvar delegate: ViewcontrollerDelegate?
}
class ViewController: UIViewController,ViewcontrollerDelegate,TwoDelegate {
var testInstance: TestClass!
overridefunc viewDidLoad() {
super.viewDidLoad()
testInstance =TestClass()
testInstance.delegate =self
testInstance.delegate?.mainFun!(string:"123456")
}
overridefunc didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func mainFun(string:NSString) {
print(string)
}
func getmessage(string:NSString) {
print(string)
}
@IBActionfunc two(_ sender:UIButton) {
let twovc =TwoViewController()
twovc.delegate =self
self.navigationController?.pushViewController(twovc, animated:true)
}
}