之前看過一段swift,一直不知道OC中的block,即swift中的閉包是怎么實現的。今天就在網上搜索了一下,同時對比了一下OC中block類型的實現方法,然后寫了一個Demo測試一下。
使用說明:
swift版本
1.聲明類型 typealias hideShowView = (Int) -> Void
2.聲明屬性 var muFunc:hideShowView?
3.傳遞參數 func didSelectedToHideView(hideFunc:@escaping (Int)->Void) { muFunc = hideFunc }
4.監聽值的變化 func tapEvent() { muFunc!(0) }
5.使用 showView.didSelectedToHideView { (para) in NSLog("%d", para) }
6.Void 是返回值類型,Int是參數類型,hideShowView是閉包的類型名稱.第5項中的para是閉包的參數名,經測試,這個參數名在使用閉包的時候可以任意修改
OC版本
.h文件
//聲明一個block類型
typedef void(^HideShowViewBlock)(int index);
//聲明一個block屬性
@property (nonatomic,copy) HideShowViewBlock hideViewBlock;
//傳遞參數的方法
- (void)didHideShowViewWithBlock:(HideShowViewBlock)hideViewBlock;
.m文件
//實現傳遞參數的函數
- (void)didHideShowViewWithBlock:(HideShowViewBlock)hideViewBlock
{
self.hideViewBlock = hideViewBlock;
}
//監聽需要傳遞值的變化
- (void)tapEvent
{
self.hideViewBlock(0);
}
swift 閉包 Demo的代碼
class ShowView: UIView
{
typealias hideShowView = (Int) -> Void
var muFunc:hideShowView?
private var viewFram:CGRect?
override init(frame:CGRect )
{
super.init(frame: frame)
self.viewFram = frame
self.backgroundColor = UIColor.gray
self.createUI()
}
func createUI()
{
var centerLabel = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: (self.viewFram?.width)!, height: 20))
centerLabel.center = self.center
centerLabel.text = "測試"
centerLabel.textColor = UIColor.white
centerLabel.textAlignment = NSTextAlignment.center
centerLabel.font = UIFont.boldSystemFont(ofSize: 16.0)
self.addSubview(centerLabel)
let tap = UITapGestureRecognizer.init(target: self, action: #selector(ShowView.tapEvent))
tap.cancelsTouchesInView = false
self.addGestureRecognizer(tap)
}
func tapEvent()
{
muFunc!(0)
}
func didSelectedToHideView(hideFunc:@escaping (Int)->Void)
{
muFunc = hideFunc
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class ViewController: UIViewController
{
let WIDTH = UIScreen.main.bounds.size.width
let HEIGHT = UIScreen.main.bounds.size.height
override func viewDidLoad()
{
super.viewDidLoad()
}
@IBAction func selectedToDoSomething(_ sender: UIButton)
{
let showView = ShowView.init(frame: CGRect.init(x: 0, y: 0, width: WIDTH/2, height: WIDTH/2))
showView.center = self.view.center
showView.didSelectedToHideView { (para) in
NSLog("%d", para)
}
self.view.addSubview(showView)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
總結
以上所述是小編給大家介紹的swift閉包和OC block類型的使用,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對html5模板網網站的支持!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!