前端之家收集整理的这篇文章主要介绍了
swift中的block,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
protocol StopTimer { func stopTimer(); } typealias InputClosureType = (String) -> Void class ViewController: UIViewController,StopTimer { var button:UIButton? = nil; var timer:Timer? = nil typealias FuncTest = (Int)->Int; var number:NSInteger = 60; var stop:StopTimer? = nil; func kj(_ name:String){} var m:((_ custom:String)->String)? // print("--=-=-=-=-=-",KM); var ms:((_ name:String)->Int)?; // var m :FuncTest?=nil; // var m = FuncTest; var testBlock:((_ kl:String)->(Int))?; // typealias funBlock = (_ number:Int)->Int; @IBOutlet weak var animateLabel: UILabel! func names(_ mg:(Int)){ print("block====%@",mg); }; var callBack = names; override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view,typically from a nib. button = UIButton(frame: CGRect(x: 20,y: 40,width: 150,height: 200)); button?.backgroundColor=UIColor.blue; button?.setTitle("60",for: UIControlState.normal) button?.addTarget(self,action: #selector(buttonClick(sender:)),for: UIControlEvents.touchUpInside) self.view.addSubview(button!) stop = self; // self.kj { (m) -> Int in // // // print("执行完成了") // // return 2; // } var m = ms; let names = ["chris","alex","bkljk "]; func sortFunc(numbers:String,numberw:String)->Bool { return numbers>numberw; } var sortm = names.sorted(by: sortFunc); print("刷选出来的结果是",sortm); print("===m",m); // self.kj { (name) -> Int in // // // // print("name的值为====>%@\n",name); // // // // // // return 2; // // }; // callBack = {(msgk) in Int // // // // // return 20; // // }; testBlock = { (kkjj:String) -> Int in print("结果是lklanxm===%@",kkjj) return 50; } let result = testBlock!("新的发现哦"); print("
输出结果是",result) } func buttonClick(sender:UIButton) { if timer==nil { let weak = self; timer = Timer.scheduledTimer(withTimeInterval: 1,repeats: true,block: { (t) in self.number -= 1; self.button?.setTitle(("\(self.number)"),for: UIControlState.normal); if self.number == 0 { self.timer?.invalidate() self.timer=nil; // if self.StopTimer != nil{ self.stop?.stopTimer(); // } // if (.m != nil) // { //// self.m = {( "hah") in Void //// //// return 20; //// } // } } }) RunLoop.current.add(timer!,forMode: RunLoopMode.commonModes) timer?.fire() } } func stopTimer() { print("停止操作了"); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }