代表在斯威夫特吗?

一个人如何去做一个代表,即 NSUserNotificationCenterDelegate在迅速?

181346 次浏览

它与 obj-c 没有什么不同。 首先,您必须在类声明中指定协议,如下所示:

class MyClass: NSUserNotificationCenterDelegate

执行情况如下:

// NSUserNotificationCenterDelegate implementation
func userNotificationCenter(center: NSUserNotificationCenter, didDeliverNotification notification: NSUserNotification) {
//implementation
}


func userNotificationCenter(center: NSUserNotificationCenter, didActivateNotification notification: NSUserNotification) {
//implementation
}


func userNotificationCenter(center: NSUserNotificationCenter, shouldPresentNotification notification: NSUserNotification) -> Bool {
//implementation
return true
}

当然,您必须设置委托,例如:

NSUserNotificationCenter.defaultUserNotificationCenter().delegate = self;

下面是对两个视图控制器之间的委托的一点帮助:

步骤1: 在 UIViewController 中创建一个协议,您将删除/发送数据。

protocol FooTwoViewControllerDelegate:class {
func myVCDidFinish(_ controller: FooTwoViewController, text: String)
}

步骤2: 在发送类(即 UIViewcontroller)中声明委托

class FooTwoViewController: UIViewController {
weak var delegate: FooTwoViewControllerDelegate?
[snip...]
}

步骤3: 使用 class 方法中的委托将数据发送给接收方法,接收方法是采用该协议的任何方法。

@IBAction func saveColor(_ sender: UIBarButtonItem) {
delegate?.myVCDidFinish(self, text: colorLabel.text) //assuming the delegate is assigned otherwise error
}

步骤4: 在接收类中采用协议

class ViewController: UIViewController, FooTwoViewControllerDelegate {

步骤5: 实现委托方法

func myVCDidFinish(_ controller: FooTwoViewController, text: String) {
colorLabel.text = "The Color is " +  text
controller.navigationController.popViewController(animated: true)
}

第六步: 在 prepareForSegue 中设置代表:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "mySegue" {
let vc = segue.destination as! FooTwoViewController
vc.colorString = colorLabel.text
vc.delegate = self
}
}

应该可以。这当然只是代码片段,但应该给你的想法。关于这段代码的详细解释,你可以点击这里查看我的博客条目:

会议议程和代表

如果你对一位代表的内幕感兴趣,我在这里写道:

在代表团的掩护下

我在@MakeAppPie 上有一些更正

首先,当您创建委托协议时,它应该符合 Class 协议。

protocol ProtocolDelegate: class {
func myMethod(controller:ViewController, text:String)
}

其次,你的代表应该软弱,以避免保留周期。

class ViewController: UIViewController {
weak var delegate: ProtocolDelegate?
}

最后,你是安全的,因为你的协议是一个可选的值。这意味着它的“ nil”消息将不会发送到此属性。这个 If判断语句类似于 obc 中的 respondToselector,但是这里所有的东西都在一行中:

if ([self.delegate respondsToSelector:@selector(myMethod:text:)]) {
[self.delegate myMethod:self text:@"you Text"];
}

上面是 obj-C 的例子,下面是 Swift 的例子。

delegate?.myMethod(self, text:"your Text")

这是我做的 大意。我也在想同样的问题,这有助于提高我的理解力。打开 Xcode 游乐场看看发生了什么。

protocol YelpRequestDelegate {
func getYelpData() -> AnyObject
func processYelpData(data: NSData) -> NSData
}


class YelpAPI {
var delegate: YelpRequestDelegate?


func getData() {
println("data being retrieved...")
let data: AnyObject? = delegate?.getYelpData()
}


func processYelpData(data: NSData) {
println("data being processed...")
let data = delegate?.processYelpData(data)
}
}


class Controller: YelpRequestDelegate {
init() {
var yelpAPI = YelpAPI()
yelpAPI.delegate = self
yelpAPI.getData()
}
func getYelpData() -> AnyObject {
println("getYelpData called")
return NSData()
}
func processYelpData(data: NSData) -> NSData {
println("processYelpData called")
return NSData()
}
}


var controller = Controller()

代表们总是把我搞糊涂,直到我意识到 委托只是为另一个类做一些工作的类。这就像有别人在那里为你做所有你不想自己做的脏活。

我写了一个小故事来说明这一点。如果你喜欢的话,可以在游乐场读一读。

很久很久以前。

// MARK: Background to the story


// A protocol is like a list of rules that need to be followed.
protocol OlderSiblingDelegate: class {
// The following command (ie, method) must be obeyed by any
// underling (ie, delegate) of the older sibling.
func getYourNiceOlderSiblingAGlassOfWater()
}


// MARK: Characters in the story


class BossyBigBrother {
    

// I can make whichever little sibling is around at
// the time be my delegate (ie, slave)
weak var delegate: OlderSiblingDelegate?
    

func tellSomebodyToGetMeSomeWater() {
// The delegate is optional because even though
// I'm thirsty, there might not be anyone nearby
// that I can boss around.
delegate?.getYourNiceOlderSiblingAGlassOfWater()
}
}


// Poor little sisters have to follow (or at least acknowledge)
// their older sibling's rules (ie, protocol)
class PoorLittleSister: OlderSiblingDelegate {


func getYourNiceOlderSiblingAGlassOfWater() {
// Little sis follows the letter of the law (ie, protocol),
// but no one said exactly how she had to respond.
print("Go get it yourself!")
}
}


// MARK: The Story


// Big bro is laying on the couch watching basketball on TV.
let bigBro = BossyBigBrother()


// He has a little sister named Sally.
let sally = PoorLittleSister()


// Sally walks into the room. How convenient! Now big bro
// has someone there to boss around.
bigBro.delegate = sally


// So he tells her to get him some water.
bigBro.tellSomebodyToGetMeSomeWater()


// Unfortunately no one lived happily ever after...


// The end.

回顾一下,制作和使用委托模式有三个关键部分。

  1. 定义工人需要做什么的 规定
  2. 具有委托变量的 老板级,它用该变量告诉工作类要做什么
  3. 采用该协议并完成所需工作的 工人阶级

真实的生活

与我们上面的专横老大哥的故事相比,代表们经常被用于以下实际应用:

  1. 通信 : 一个类需要向另一个类发送一些信息。
  2. 定制 : 一个类希望允许另一个类定制它。

最重要的部分是,这些类不需要事先了解彼此的任何信息,除非委托类符合所需的协议。

我强烈推荐阅读以下两篇文章。它们甚至比 文件更好地帮助我理解代表们。

还有一个音符

引用不属于自己的其他类的委托应该使用 weak关键字,以避免强引用周期。有关详细信息,请参阅 这个答案

上面的解决方案似乎有点耦合,同时避免在其他控制器中重用相同的协议,这就是为什么我使用通用类型擦除来提供更强类型的解决方案。

@noreturn public func notImplemented(){
fatalError("not implemented yet")
}




public protocol DataChangedProtocol: class{
typealias DataType


func onChange(t:DataType)
}


class AbstractDataChangedWrapper<DataType> : DataChangedProtocol{


func onChange(t: DataType) {
notImplemented()
}
}




class AnyDataChangedWrapper<T: DataChangedProtocol> : AbstractDataChangedWrapper<T.DataType>{


var base: T


init(_ base: T ){
self.base = base
}


override func onChange(t: T.DataType) {
base.onChange(t)
}
}




class AnyDataChangedProtocol<DataType> : DataChangedProtocol{


var base: AbstractDataChangedWrapper<DataType>


init<S: DataChangedProtocol where S.DataType == DataType>(_ s: S){
self.base = AnyDataChangedWrapper(s)
}


func onChange(t: DataType) {
base.onChange(t)
}
}






class Source : DataChangedProtocol {
func onChange(data: String) {
print( "got new value \(data)" )
}
}




class Target {
var delegate: AnyDataChangedProtocol<String>?


func reportChange(data:String ){
delegate?.onChange(data)
}
}




var source = Source()
var target = Target()


target.delegate = AnyDataChangedProtocol(source)
target.reportChange("newValue")

输出 : < em > 得到新值 newValue

代表们在 SWIFT 2

我用 viewcontrollers.in 代理的例子来解释这种情况,Second VC 对象将数据发送回第一视图控制器。

带协议声明的类

protocol  getDataDelegate  {
func getDataFromAnotherVC(temp: String)
}




import UIKit
class SecondVC: UIViewController {


var delegateCustom : getDataDelegate?
override func viewDidLoad() {
super.viewDidLoad()
}


override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func backToMainVC(sender: AnyObject) {
//calling method defined in first View Controller with Object
self.delegateCustom?.getDataFromAnotherVC(temp: "I am sending data from second controller to first view controller.Its my first delegate example. I am done with custom delegates.")
self.navigationController?.popViewControllerAnimated(true)
}
    

}

在第一视图控制器中,协议的一致性在这里完成:

class ViewController: UIViewController, getDataDelegate

第一视图控制器(ViewController)中的协议方法定义

func getDataFromAnotherVC(temp : String)
{
// dataString from SecondVC
lblForData.text = dataString
}

在从第一视图控制器(视图控制器)推第二 VC

let objectPush = SecondVC()
objectPush.delegateCustom = self
self.navigationController.pushViewController(objectPush, animated: true)

头等舱:

protocol NetworkServiceDelegate: class {
        

func didCompleteRequest(result: String)
}




class NetworkService: NSObject {


weak var delegate: NetworkServiceDelegate?
    

func fetchDataFromURL(url : String) {
delegate?.didCompleteRequest(result: url)
}
}

第二类:

class ViewController: UIViewController, NetworkServiceDelegate {
    

let network = NetworkService()
    

override func viewDidLoad() {
super.viewDidLoad()
network.delegate = self
network.fetchDataFromURL(url: "Success!")
}


 

    

func didCompleteRequest(result: String) {
print(result)
}




}

委托是一种设计模式,允许一个对象在特定事件发生时向另一个对象发送消息。 假设一个对象 A 调用一个对象 B 来执行一个操作。一旦操作完成,对象 A 应该知道 B 已经完成了任务并采取了必要的操作,这可以在委托的帮助下实现! 这里是一个教程实现代表一步一步的迅速3

教程连结

简单的例子:

protocol Work: class {
func doSomething()
}


class Manager {
weak var delegate: Work?
func passAlong() {
delegate?.doSomething()
}
}


class Employee: Work {
func doSomething() {
print("Working on it")
}
}


let manager = Manager()
let developer = Employee()
manager.delegate = developer
manager.passAlong() // PRINTS: Working on it

迅捷4.0版

在需要向其他类发送数据或提供某些功能的类上创建委托

喜欢

protocol GetGameStatus {
var score: score { get }
func getPlayerDetails()
}

然后在类中,向这个委托进行确认

class SnakesAndLadders: GetGameStatus {
func getPlayerDetails() {


}
}

非常容易一步一步(100% 的工作和测试)

Step 1: Create method on first view controller 步骤1: 在第一个视图控制器上创建方法

 func updateProcessStatus(isCompleted : Bool){
if isCompleted{
self.labelStatus.text = "Process is completed"
}else{
self.labelStatus.text = "Process is in progress"
}
}

Step 2: 设置委托,同时推到第二视图控制器

@IBAction func buttonAction(_ sender: Any) {


let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "secondViewController") as! secondViewController
secondViewController.delegate = self
self.navigationController?.pushViewController(secondViewController, animated: true)
}

第三步: 设置像

类 ViewController: UIViewController,进程状态代理{

步骤4: 创建协议

protocol ProcessStatusDelegate:NSObjectProtocol{
func updateProcessStatus(isCompleted : Bool)
}

第五步: 取一个变量

var delegate:ProcessStatusDelegate?

步骤6: 然后回到前一个视图控制器调用委托方法,这样第一个视图控制器会用数据通知

@IBAction func buttonActionBack(_ sender: Any) {
delegate?.updateProcessStatus(isCompleted: true)
self.navigationController?.popViewController(animated: true)
}


@IBAction func buttonProgress(_ sender: Any) {
delegate?.updateProcessStatus(isCompleted: false)
self.navigationController?.popViewController(animated: true)


}

下面是现实生活中的委托场景
让我们创建我们自己的 UITextField 和 UITextField 委托

// THE MYSTERIOUS UITEXTFIELD


protocol UITextFieldDelegate {
func textFieldDidChange(_ textField: UITextField) -> Void
}


class UITextField {
var delegate: UITextFieldDelegate?
private var mText: String?
var text: String? {
get {
return mText
}
}
    

init(text: String) {
        

}
    

init() {
        

}
    

func setText(_ text: String) {
mText = text
delegate?.textFieldDidChange(self)
}


}
// HERE IS MY APP


class Main {
    

let textfield = UITextField()
    

func viewDidLoad() {
print("viewDidLoad")
textfield.delegate = self
textfield.setText("Hello")
}
    

}


extension Main: UITextFieldDelegate {
    

func textFieldDidChange(_ textField: UITextField) {
print(textField.text ?? "No string")
}
    

}


let main = Main()
main.viewDidLoad()


此处简单的代码委托示例:

//MARK: - Protocol ShowResult
protocol ShowResult: AnyObject {
func show(value: Int)
}


//MARK: - MyOperation Class
class MyOperation {
weak var delegate: ShowResult?


func sum(fNumber: Int, sNumber: Int) {
delegate?.show(value: fNumber + sNumber)
}
}


//MARK: - ViewController Class
class ViewController: UIViewController,ShowResult {
var myOperation: MyOperation?


override func viewDidLoad() {
super.viewDidLoad()
loadMyOperation()
myOperation?.delegate = self
myOperation?.sum(fNumber: 100, sNumber: 20)
}


private func loadMyOperation() {
if myOperation == nil {
myOperation = MyOperation()
}
}


func show(value: Int) {
print("value: \(value)")
}
}

在雨燕5号

我是一个初学者,我认为这是最容易理解的实际情况

注意: 任何即兴表演都是最受欢迎的

protocol APIService {
func onSuccessResponse() -> AnyObject
func onFailureResponse() -> AnyObject
}


class APIHelper{


var delegate : APIService?


func postUsersDataAPI() {
//assuming API communication is success
if(success){
let _: AnyObject? = delegate?.onSuccessResponse()
}else if(failure){
let _: AnyObject? = delegate?.onFailureResponse()
}
}


func getAllUsersAPI() {
//assuming API communication is success
if(success){
let _: AnyObject? = delegate?.onSuccessResponse()
}else if(failure){
let _: AnyObject? = delegate?.onFailureResponse()
}
}
}




class ViewController:UIViewController,APIService {


func onSuccessResponse() -> AnyObject {
print("onSuccessResponse") as AnyObject
}


func onFailureResponse() -> AnyObject {
print("onFailureResponse") as AnyObject
}


@IBAction func clickBtnToPostUserData(_ sender: Any) {
let apiHelper = APIHelper()
apiHelper.delegate = self
apiHelper.postAPI()
}