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

swift-delegate(代理)或者block传值

2015-10-18 10:13 519 查看
1:delegate或者block传值

import UIKit
class ViewController: UIViewController,TestDelegatePassValueDelegate {

@IBOutlet weak var TFContent: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

@IBAction func delegateOrBlockBtnClick(sender: AnyObject) {
TFContent.text = ""
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let testVCtl = storyBoard.instantiateViewControllerWithIdentifier("TestDelegateOrBlockViewController") as!TestDelegateOrBlockViewController;
/**设置代理*/
testVCtl.delegate = self
/**block回调传值*/
testVCtl.passValueUseBlock { (valueString) -> Void in

self.TFContent!.text = valueString  as String

}
self.navigationController!.pushViewController(testVCtl, animated: true);

}
/**代理函数*/
func passValueUseDelegate(valueString: NSString)
{
self.TFContent!.text = valueString as String
}

}
import UIKit
import Foundation
/**定义一个block*/
typealias TestBlockCompleteHandler = (valueString: NSString)->Void
/**声明定义协议*/
protocol TestDelegatePassValueDelegate:NSObjectProtocol
{
func passValueUseDelegate(valueString: NSString)

}

class TestDelegateOrBlockViewController: UIViewController
{

@IBOutlet weak var TFContent: UITextField!
var delegate:TestDelegatePassValueDelegate?

var myBlockHandler:TestBlockCompleteHandler?
override func viewDidLoad() {
super.viewDidLoad()

// Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

//MARK: - 用代理来实现传值
@IBAction func delegateBtnClick(sender: AnyObject)
{

TFContent.resignFirstResponder()
if ((delegate != nil) && (delegate?.respondsToSelector("passValueUseDelegate:") != nil))
{
delegate?.passValueUseDelegate(TFContent.text!)

}
self.navigationController?.popViewControllerAnimated(true)

}

//MARK: - 用block来实现传值
@IBAction func blockBtnClick(sender: AnyObject)
{

TFContent.resignFirstResponder()
myBlockHandler?(valueString: self.TFContent.text!)
self.navigationController?.popViewControllerAnimated(true)

}

func passValueUseBlock(blockHandler: TestBlockCompleteHandler)
{
myBlockHandler = blockHandler

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: