您的位置:首页 > 移动开发 > Swift

swift delegate代理和block的使用

2016-11-18 17:04 309 查看

不多说直接上代码

声明

//  TestDelegateView.swift
//  blockAndDelegate
//
//  Created by jarvis on 2016/11/18.
//  Copyright © 2016年 jarvis jiang. All rights reserved.
import UIKit
@objc protocol testDelegate {
//代理声明
@objc optional func ClickEd(str: String)
}
class TestDelegateView: UIView {
var delegate: testDelegate?
// 声明block
var buttonBlock :((_ str:String)->())?

override init(frame:CGRect) {
super.init(frame: frame)
self.backgroundColor=UIColor.green
let label:UILabel = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 20))
label.text="顶你个肺"
label.textAlignment = .center
self.addSubview(label)
let button : UIButton = UIButton.init(frame: CGRect.init(x: 0, y: 25, width: 40, height: 40))
button.addTarget(self, action: #selector(buttonClicked(_:)) , for: .touchUpInside)
button.backgroundColor=UIColor.red
self.addSubview(button)
}
func buttonClicked(_ button:UIButton) ->  Void{
print("buttonCLick")
delegate?.ClickEd!(str: "代理点击")
buttonBlock?("block点击")

}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/

}


调用

import UIKit
import Alamofire
class ViewController: UIViewController,testDelegate{

override func viewDidLoad() {
super.viewDidLoad()
initView()

Alamofire.request("http://chenggua.com/api.php?r=verupdate/verupdate", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).validate().responseJSON { (response) in
switch response.result{
case.success:
print("success------\(response)")
case.failure(let error):
print(" error------|\(error)--");
}

}

// Do any additional setup after loading the view, typically from a nib.
}
func initView() -> Void {
let tt = TestDelegateView.init(frame: CGRect.init(x: 0, y: 210, width: UIScreen.main.bounds.width, height: 100))
tt.delegate=self
tt.buttonBlock = { (str:String) -> () in
print("------blockClick---\(str)")
}
self.view.addSubview(tt)

}
// MARK: -----testDelegate
func ClickEd(str: String) {
print("-----clickString-------\(str)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  delegate swift block