本文只是用一个小Demo来说明swift中协议和代理的用法
首先自定义了一个view,并在view中实现了定义了协议方法,然后在controller中使用自定义view并实现协议和代理
自定义view代码如下:
import UIKit
@objc protocol CustomViewDelegae {
func clickAtIndex(index:NSInteger)
}
class CustomView: UIView {
weak var delegate: CustomViewDelegae?
var button1:UIButton?
var button2:UIButton?
init(delegate: CustomViewDelegae) {
super.init(frame: CGRectZero)
self.delegate = delegate
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupUI() {
self.button1 = UIButton.init(type: .Custom)
self.button1?.backgroundColor = UIColor.redColor()
self.button1?.frame = CGRectMake(0, 65, 60, 30)
self.button1?.tag = 1
self.button1?.addTarget(self, action: #selector(buttonClick), forControlEvents: .TouchUpInside)
self.addSubview(self.button1!)
self.button2 = UIButton.init(type: .Custom)
self.button2?.backgroundColor = UIColor.blueColor()
self.button2?.frame = CGRectMake(0, 100, 60, 30)
self.button2?.tag = 2
self.button2?.addTarget(self, action: #selector(buttonClick), forControlEvents: .TouchUpInside)
self.addSubview(self.button2!)
}
func buttonClick(sender:UIButton){
clickAtIndex(sender.tag)
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
extension CustomView {
func clickAtIndex(index:NSInteger) {
delegate?.clickAtIndex(index)
print("you have clicked:",index)
}
}
然后是controller中的代码:
import UIKit
class ViewController: UIViewController,CustomViewDelegae {
var name:String?
var cv:CustomView?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
configViews()
}
func configViews() {
self.title = "首页"
self.view.backgroundColor = UIColor.whiteColor()
setupData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController {
func setupData(){
self.cv = CustomView.init(delegate: self)
self.cv!.frame = CGRectMake(10, 10, 300, 300)
self.cv!.backgroundColor = UIColor.yellowColor()
self.view.addSubview(self.cv!)
}
func clickAtIndex(index: NSInteger) {
if index == 1 {
let vc = SecondViewController()
self.navigationController?.pushViewController(vc, animated: true)
}
else
{
print("click two")
}
}
}
以上就是swift中代理的写法,欢迎指正交流。