一:闭包(闭包)
比如我们在OC需要在View定定义一个block,然后在对应的控制器里面使用block保存对应的砝码快,然后返回这里执行,那在OC是类似的,只是名称不同语法有那么一点区别而已
首先在View中声明一个闭包别名,根据我们需要传递的参数
/// 闭包的声明 typealias iCocosClosure = (string: String) ->Void
然后声明一个闭包属性,并且实现初始化方法
var iCocosBlock: iCocosClosure? //将函数指针赋值给myClosure闭包,该闭包中涵盖了someFunctionThatTakesAClosure函数中的局部变量等的引用 func initWithClosure(closure: iCocosClosure?) { iCocosBlock = closure }
最后在摇执行的方法里面判断就并且执行就可以
//判空 if (iCocosBlock != nil){ //闭包隐式调用someFunctionThatTakesAClosure函数:回调。 iCocosBlock!(string: "name") }
这个时候控制器里面就很简单了,只需要传入对应的代码保存到闭包里面
textField.initWithClosure { (string) -> Void in if (self.textField?.text.isEmpty != nil) { return; } self.tagButtons.removeLast() }
二:代理
首先定义一个代理协议,和对应的代理方法
//协议,定义代理要实现的方法 protocol iCocosViewControlDelegate{ func changeLabel(newString:String) }
定义一个Delegate对象
var delegate:iCocosViewControlDelegate?
判断是否遵守这个代理协议,遵守则执行代理方法
if (delegate) { delegate?.changeLabel("iCocos") }
在接受代理的控制器或者View中实现下面的代理
设置代理 vc.delegate = self
遵守协议iCocosViewControlDelegate
在对应的控制器中遵守协议iCocosViewControlDelegate,实现代理方法
实现代理方法
func changeLabel(newString:String) {
实现大礼方法的代理
这里主意参数的传递
}
三:通知,跟OC几乎一样
添加一个通知,并且实现同步方法
- NSNotificationCenter.defaultCenter().addObserver(self, selector: "Notification", name: "iCocos", object: self)
func Notification() { print("") }
在对应的控制器发布通知
- NSNotificationCenter.defaultCenter().postNotificationName("iCocos", object: self, userInfo: nil)
四:segue实现控制器跳转
1 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 2 3 if segue.identifier == "showDetail" { 4 destinationController.navigationItem.title = "摇到的菜" 5 destinationController.tempCaipin = self.showArray //传值 6 } 7 }
五:NSUserDefaults(不过这个用的比较多的是数据持久化,这里严格来说不能算传值)
1 func cacheSetString(key: String,value: String){ 2 var userInfo = NSUserDefaults() 3 userInfo.setValue(value, forKey: key) 4 } 5 6 func cacheGetString(key: String) -> String{ 7 var userInfo = NSUserDefaults() 8 var tmpSign = userInfo.stringForKey(key) 9 return tmpSign! 10 }
经典错误
一:可选类型错误
- tipBtn.setTitle("添加表情:\(self.textField?.text)", forState: UIControlState.Normal)
解决办法
- tipBtn.setTitle("添加表情:\(self.textField!.text)", forState: UIControlState.Normal)
二:可选链
提示插入
插入子后��提示删除
这个时候只需使用显示就可以
版权声明:欢迎转载,请贴上源地址: http://www.cnblogs.com/iCocos/(iOS梦工厂)
更多精彩请关注github:https://github.com/al1020119?tab=repositories
本博文由博主(iCocos)独立编写或者借鉴别人的好文章进行修改而成,如果不对的地方望指正,谢谢! 笔者所有相关博客已转至git博文:http://al1020119.github.io/此博文不会再更新,也很少会回复,如有疑问请联系我!Q Q:2211523682/790806573微信:18370997821/13148454507微博WB:http://weibo.com/u/3288975567?is_hot=1git博文:http://al1020119.github.io/github:https://github.com/al1020119