swift delegate 和 block 使用
delegate使用
//自定义cell 代码importUIKit//声明代理协议protocolbtnClickDelegate{//代理方法funcbtnclickMethod(tag:Int)}classJRLoginTableViewCell:UITableViewCell{//代理属性publicvardelegate:btnClickDelegate?@IBOutletweakvargetCodeBtn:UIButton!@IBOutletweakvarcodeTF:UITextField!@IBOutletweakvarphoneTF:UITextField!overridefuncawakeFromNib(){super.awakeFromNib()// Initialization code}@IBActionfuncgetCodeClick(_sender:Any){// print("获取验证码")if(delegate!=nil){delegate?.btnclickMethod(tag:1)}}@IBActionfunccommitClick(_sender:UIButton){// print("马上开启")if(delegate!=nil){delegate?.btnclickMethod(tag:2)}}@IBActionfunctextEidDidEnd(_sender:UITextField){print(sender.textasAny)}overridefuncsetSelected(_selected:Bool,animated:Bool){super.setSelected(selected,animated:animated)// Configure the view for the selected state}}
viewController调用
//遵守协议classJRMainViewController:JRRootViewController,btnClickDelegate,UITableViewDelegate,UITableViewDataSource{}
//设置代理letloginCell=tableView.dequeueReusableCell(withIdentifier:"JRLoginTableViewCell",for:indexPath)as!JRLoginTableViewCellloginCell.selectionStyle=.noneloginCell.delegate=self;returnloginCell
//实现协议方法//MARK: - btnClickDelegatefuncbtnclickMethod(tag:Int){print(tag)iftag==1{//获取验证码getPhoneCode(phoneStr:"123213")}elseiftag==2{//登录}}
block使用
//自定义cell 代码
importUIKitclassJRLoginTableViewCell:UITableViewCell{//代理属性@IBOutletweakvargetCodeBtn:UIButton!@IBOutletweakvarcodeTF:UITextField!@IBOutletweakvarphoneTF:UITextField!//定义blocktypealiasfucBlock=(String)->()//创建block变量varblockproerty:fucBlock!overridefuncawakeFromNib(){super.awakeFromNib()// Initialization code}@IBActionfunctextEidDidEnd(_sender:UITextField){print(sender.textasAny)}@IBActionfuncgetCodeClick(_sender:Any){// print("获取验证码")//block调用iflet_=blockproerty{blockproerty("1212")}}@IBActionfunccommitClick(_sender:UIButton){// print("马上开启")iflet_=blockproerty{blockproerty("334344")}}overridefuncsetSelected(_selected:Bool,animated:Bool){super.setSelected(selected,animated:animated)// Configure the view for the selected state}}
viewController调用
letloginCell=tableView.dequeueReusableCell(withIdentifier:"JRLoginTableViewCell",for:indexPath)as!JRLoginTableViewCellloginCell.selectionStyle=.none//block 回调loginCell.blockproerty={(backMsg)inprint(backMsg);}returnloginCell
网友评论