Swift 协议代理的使用和OC的使用步骤是一致.
效果图
具体使用步骤
在SecondViewController里面声明一个协议
1.声明一个协议方法
/** * 声明一个协议 */
protocol SecondViewControllerDelegate{
// 协议方法
func changeText(str:String)
}
协议名:SecondViewControllerDelegate
2.声明一个SecondViewControllerDelegate对象
// 声明一个协议的属性
@H_301_22@var @H_301_22@delegate : SecondViewControllerDelegate?
3.关联协议方法
func textFieldDidEndEditing(@H_301_22@textField: UITextField) {
// 协议传值
self.delegate?.changeText(@H_301_22@textField.@H_301_22@text!)
}
在ViewController里面
4.关联协议SecondViewControllerDelegate
5.代理的关联
@IBAction func nextBtnClick(sender: UIButton) {
@H_301_22@let sVC = SecondViewController()
sVC.delegate = @H_301_22@self // 关联代理
@H_301_22@self.navigationController?.pushViewController(sVC,animated: @H_301_22@true);
}
6.实现协议方法
func changeText(@H_301_22@str: String) { @H_301_22@self.showLabel.text = @H_301_22@str }
总结
- 代理协议的使用步骤就是这6步,在制作协议的地方和使用协议的地方都是3步,每一步缺一不可.
- 代理的反向传值的使用
- pushViewController方法的使用
OC版本协议和代理
参见博客: