swift中闭包的传值用法

这两天在练习swift的项目中遇到了一个难题,就是闭包的使用,在网络封装中或者是界面传值中,用OC中的block块传值很方便直观,在swift中却有些晕,经过搜索资料,终于解决了

主要是闭包的定义和使用,模拟一个场景,TopScrollView中点击按钮,利用闭包将所需的参数传递给控制器HomeViewController使用,控制器中调用闭包

1.在TopScrollView中定义闭包

class TopScrollView: UIScrollView {
    var config:ItemConfig!
    var currentIndex:Int = 0
    var lineView:UIView!
    var tapAnimation:Bool?
    //闭包的两种定义方法
    //1.
    typealias blockClosure = (Int,Bool) ->Void
    var didClickItemBlock:blockClosure?
    //2.
    //var itemDidClickBlock:((Int,Bool) ->Void)?
}
  • 闭包的定义就完成了,下面是触发闭包,用来传值
    @objc private func itemButtonClick(button:UIButton) {
    
        currentIndex = button.tag - 100
        if tapAnimation! {
        }else {
            changeItemColor(index: Float(currentIndex))
            changeLine(index: Float(currentIndex))
        }
        changeScrollOffset(index: Float(currentIndex))
//        topScrollViewDelegate!.topScrollViewDidClickItem(index: currentIndex, animation: tapAnimation!)
        if didClickItemBlock != nil {
            didClickItemBlock!(currentIndex,tapAnimation!)
        }
    }
  • 最后是在控制器中接收传递过来的值,做相应操作
    private func setupTopScrollView() {
    
        let config = ItemConfig()
        config.itemWidth = view.width / 4.0
        
        topScrollView = TopScrollView(frame: CGRect(x: 0, y: 0, width: view.bounds.size.width, height: 40))
        topScrollView.config = config
        let array = ["视频","直播","图集","小清新","程序设计","新闻","天气预报","段子","政治"]
        topScrollView.setupDataSource(array:array as NSArray)
        topScrollView.topScrollViewDelegate = self
        view.addSubview(topScrollView)
        topScrollView.didClickItemBlock = { (index,tapAnimation) in
        self.mainCollectionView.scrollRectToVisible(CGRect(x: CGFloat(index) * self.mainCollectionView.width, y: 0.0, width: self.mainCollectionView.width, height: self.mainCollectionView.height), animated: tapAnimation)  
        }
    }

整个闭包的使用就是这样,其实和block块很像,弄懂了也不是那么可怕,下面附一个简单网络请求中的闭包使用

class NetworkTool: NSObject {
    
    typealias successBlock = (Any?) ->Void
    typealias failureBlock = (NSError) ->Void
    func GetRequest(urlString:String,parameters:[String:Any]?,success:successBlock?,failure:failureBlock?) {
        
        let manager = AFHTTPSessionManager()
        
        manager.get(urlString, parameters: parameters, progress: {(progress) in
        
        }, success: {(task, response) in
        
            if success != nil {
            
                success!(response)
            }
            
        }, failure: {(task, error) in
        
            if failure != nil {
            
                failure!(error as NSError)
            }
        })
        
        
    }
    
}

你可能感兴趣的:(swift中闭包的传值用法)