闭包及使用

闭包类型

  //MARK:1--带参数闭包
    open var myClosures:((_ sender:UIButton) -> ())?
    //MARK:2--不带参数闭包
    open var closure: (()->Void)?
    //MARK:3--逃逸闭包
    //myEscapingClosures(dosomething:String,finishCallClosure: @escaping (_ result:Any) -> ()){}
open func myEscapingClosures(dosomething:String,finishCallClosure: (@escaping (_ result:Any) -> ())){
        
        var aaa = String()
        DispatchQueue.global().async {
            DispatchQueue.global().asyncAfter(deadline: .now() + 10) {
                 aaa = dosomething + dosomething
                
                 finishCallClosure(aaa)
            }
        }
    }

    //MARK:--尾随闭包
    //尾随闭包是一个书写在函数括号之后的闭包表达式,函数支持将其作为最后一个函数调用。
    /** func backClosure(参数1: String, 参数2: String, 闭包closure: (closure的参数1,closure的参数2) -> closure的返回值类型) -> 函数的返回值类型 {//函数结束时正常调用自身参数->闭包函数  return closure(参数) }
    */
 func backClosure(str1:String,str2:String,closure:(_ name1:String,_ name2:String) ->(String)) ->String{
        
        //或者做些别的
        return closure(str1,str2)
    }

cell中使用时例子

import UIKit
import SnapKit
class myNewsCell: UITableViewCell {
     //MARK:1--带参数闭包
    open var myClosures:((_ sender:UIButton) -> ())?
    //MARK:2--不带参数闭包
    open var closure: (()->Void)?
    //MARK:3--逃逸闭包
    //myEscapingClosures(dosomething:String,finishCallClosure: @escaping (_ result:Any) -> ()){
    //MARK:--尾随闭包
    //尾随闭包是一个书写在函数括号之后的闭包表达式,函数支持将其作为最后一个函数调用。
    /** func backClosure(参数1: String, 参数2: String, 闭包closure: (closure的参数1,closure的参数2) -> closure的返回值类型) -> 函数的返回值类型 {//函数结束时正常调用自身参数->闭包函数  return closure(参数) }
    */
    override func awakeFromNib() {
        super.awakeFromNib()
        
    }
    
    func backClosure(str1:String,str2:String,closure:(_ name1:String,_ name2:String) ->(String)) ->String{
        
        
        return closure(str1,str2)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        snpLayoutSubViews()
        
    }
    
    func snpLayoutSubViews(){
        
        self.contentView.addSubview(iconImg)
        self.contentView.addSubview(button)
        self.contentView.addSubview(contentLabel)
        contentLabel.backgroundColor = UIColor.green
        button.snp.makeConstraints { (make) in
            make.right.equalTo(self.contentView).offset(-10)
            make.width.equalTo(30)
            make.height.equalTo(30)
            make.top.equalTo(self.iconImg)
        }
        
        contentLabel.snp.makeConstraints { (make) in
            make.left.equalTo(self.iconImg.snp_rightMargin).offset(10)
            make.right.equalTo(self.contentView).offset(-10)
            make.top.equalTo(self.iconImg).offset(40)
            make.bottom.equalTo(-10)
        }
        
    }
    
    lazy var button:UIButton = {
        var button = UIButton()
        button.backgroundColor = UIColor.orange
        button.layer.cornerRadius = 5
        button.layer.masksToBounds = true
        button.addTarget(self, action: #selector(buttonClick(sender:)), for: .touchUpInside)
        return button
    }()
    
    @objc func buttonClick(sender:UIButton){
        
        sender.tag = 2
        if self.myClosures != nil{
            
            myClosures!(sender)
        }
        if closure != nil {
            closure!()
        }
    }
    
    
    //MARK:-- 逃逸闭包
    //class func requestData(type:MethodType,URLString:String,parameters:[String:Any],finishCallback: @escaping (_ result:AnyObject) ->()){
    open func myEscapingClosures(dosomething:String,finishCallClosure: (@escaping (_ result:Any) -> ())){
        
        var aaa = String()
        DispatchQueue.global().async {
            DispatchQueue.global().asyncAfter(deadline: .now() + 10) {
                 aaa = dosomething + dosomething
                
                 finishCallClosure(aaa)
            }
        }
    }
    
    //MARK:-- 图片
    lazy var iconImg:UIImageView = {
        var iconImg = UIImageView(frame: CGRect(x: 10, y: 10, width: 30, height: 30))
        iconImg.backgroundColor = UIColor.red
        iconImg.layer.cornerRadius = 5
        iconImg.layer.masksToBounds = true
        return iconImg
    }()
    //MARK:--
    lazy var contentLabel:UILabel = {
        var contentLabel = UILabel()//frame: CGRect(x: 50, y: 10, width: 200, height: 0)
        contentLabel.numberOfLines = 0
        contentLabel.backgroundColor = UIColor.green
        return contentLabel
    }()
    
    
    open var dataArr: Array = [] {
        
      didSet {
    
//        dataArr.forEach { (str) in
//            contentLabel.text = str
//           let size = contentLabel.sizeThatFits(CGSize(width: contentLabel.width, height: CGFloat(MAXFLOAT)))
//            contentLabel.frame = CGRect(x: 50, y: 10, width: 200, height: size.height)
//        }
        
     }
        
    }
    
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

下面是控制器中使用例子

import UIKit
import SnapKit
class myNewsVC: UIViewController {

    var cell:myNewsCell!
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.addSubview(newsTableView)
        
    }
    
    
    lazy var newsTableView: UITableView = {
        var newsTableView = UITableView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.height))
        newsTableView.delegate = self
        newsTableView.dataSource = self
        newsTableView.estimatedRowHeight = 70
        newsTableView.rowHeight = UITableView.automaticDimension;
        newsTableView.register(myNewsCell.self, forCellReuseIdentifier: "newscellId")
        return newsTableView
    }()
    
//    lazy var dataArray : [String] = {
//        () -> [String] in
//        return ["why", "lmj", "lnj"]
//    }()
    
   lazy var dataArr:Array = {
      () -> [String] in
        
        return ["车辆消息","系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息","系统消统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息系统消息"]
    }()
}

extension myNewsVC:UITableViewDataSource,UITableViewDelegate{
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "newscellId", for: indexPath) as! myNewsCell
        
        cell.contentLabel.text = dataArr[indexPath.row]
        
        //MARK:1--带有返回值的闭包
        cell.myClosures = { sender in
            
            print(sender.tag)
        }
        //MARK:2--没有返回值的闭包
        cell.closure = {
            
            
        }
        //MARK:3--逃逸闭包
        cell.myEscapingClosures(dosomething: "name") { (make) in
            
            print("这是得到的值",make)
        }
        return cell
    }
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if indexPath.row == 0 {
            
        }else{
            
        }
        
    }


}

你可能感兴趣的:(闭包及使用)