swift 代理传值
swift中的代理传值跟oc中的用法基本一样,都是用于反向传值,这里假设a界面向b界面传值为正向传值,则:
在b界面
//设置代理方法
protocol BaseOneControllerDelegate {
func sendMessage(message:NSString?)
}
class BaseOneController: UIViewController {
//定义代理属性
var delegate:BaseOneControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
let segMentArray = ["代理返回"]
segment = UISegmentedControl(items: segMentArray)
segment.frame = CGRect.init(x: 0, y: 100, width: kWidth, height: 30)
//添加动作事件
segment.addTarget(self, action: #selector(BaseOneController.segmentAction(sender:)), for: UIControlEvents.valueChanged)
self.view.addSubview(segment)
}
func segmentAction(sender:UISegmentedControl) {
print("我点击了第 \(sender.selectedSegmentIndex) 选项")
if sender.selectedSegmentIndex == 0 {
//完成代理事件
if (delegate != nil) {
self.delegate?.sendMessage(message: "代理传值成功,点击返回按钮")
_ = self.navigationController?.popViewController(animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
在a界面,首先添加b界面的代理BaseOneControllerDelegate
let baseOne = BaseOneController()
//跳转的时候记得设置好代理
baseOne.delegate = self
self.navigationController?.pushViewController(baseOne, animated: true)
//代理方法
func sendMessage(message: NSString?) {
print("\(message)")
}