您的位置:首页 > 移动开发 > Swift

swift视图与控制器之间的简单传值

2016-08-31 21:50 295 查看
第一种 代码块(oc)

1 新建一个swift文件(NSobject、view、controller等),代码如下

class switfBlock: UIView{
typealias testBlock = (String)->()//声明代码块
var blo: testBlock? //代码块属性
func nameBlock()  {
self.blo!("fdasf fhjkasdf fajkfh")
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}


2.使用方式

let  switfBlocks = switfBlock()
switfBlocks.blo = {str in
print("fa:\(str)")
}


第二种 协议(oc)

1 新建一个swift文件(NSobject、view、controller等),代码如下

protocol swiftDelegateProtocol {//声明协议
func testDelegate(str: String)//方法
}
class swiftDelegate: UIView {
var delegatessde : swiftDelegateProtocol?//属性协议
func namede()  {
delegatessde?.testDelegate("fdasf\(swiftShare.shareDlin.names)")//开始传值
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}


2使用方法

class ViewController: UIViewController, swiftDelegateProtocol {
override func viewDidLoad() {
super.viewDidLoad()
let  swiftDelegates = swiftDelegate()
swiftDelegates.delegatessde = self
swiftDelegates .namede()
}
func testDelegate(str: String) {//调用协议
print("de:\(str)")
}
}


第三种 通知(oc)

1 新建一个swift文件(NSobject、view、controller等),代码如下

class swiftNotification: UIView {

func resigerNotifi()  {
let notifi = NSNotificationCenter.defaultCenter()

notifi.addObserverForName("notifid", object: nil, queue: nil,usingBlock: { (notifis: NSNotification) in
print("no:\(notifi)")
})//方式一

let operationQueue = NSOperationQueue.mainQueue()
notifi.addObserverForName("notifiQu", object: nil, queue: operationQueue) { (notofis: NSNotification) in
print("noQ:\(notifi)")
}//方式2️⃣
//方式3
notifi.addObserver(self, selector:#selector(self.notifiNmae(_:)), name: "nofiNmae", object: nil)
notifi.addObserver(self, selector:#selector(notifiNmae(_:)), name: "nofiNmae", object: nil)

}
func notifiNmae(notifis: NSNotification) {
let share = swiftShare.getdataShare2()
print("noN:\(notifis)+_\(share.names)")
}

deist{//消除


NSNotificationCenter.defaultCenter().removeObserver(self)//移除通知

}

/*

// Only override drawRect: if you perform custom drawing.

// An empty implementation adversely affects performance during animation.

override func drawRect(rect: CGRect) {

// Drawing code

}

*/

}

2 使用方式

NSNotificationCenter.defaultCenter().postNotificationName(“notifid”, object: nil)//方式1

NSNotificationCenter.defaultCenter().postNotificationName(“notifiQu”, object: nil)//方式2

NSNotificationCenter.defaultCenter().postNotificationName(“nofiNmae”, object: nil)//方式3
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  swift class oc