代表们迅速?

use*_*173 129 delegates delegation swift

如何做一个代表,即NSUserNotificationCenterDelegate快速?

Mak*_*Pie 224

以下是两个视图控制器之间代表的一些帮助:

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

protocol FooTwoViewControllerDelegate:class {
    func myVCDidFinish(_ controller: FooTwoViewController, text: String)
}
Run Code Online (Sandbox Code Playgroud)

Step2: 在发送类中声明委托(即UIViewcontroller)

class FooTwoViewController: UIViewController {
    weak var delegate: FooTwoViewControllerDelegate?
    [snip...]
}
Run Code Online (Sandbox Code Playgroud)

步骤3: 在类方法中使用委托将数据发送到接收方法,接收方法是采用该协议的任何方法.

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

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

class ViewController: UIViewController, FooTwoViewControllerDelegate {
Run Code Online (Sandbox Code Playgroud)

第5步:实现委托方法

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

第6步:在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
    }
}
Run Code Online (Sandbox Code Playgroud)

那应该有用.这当然只是代码片段,但应该给你一个想法.有关此代码的详细说明,您可以访问我的博客条目:

segues和代表

如果你对代表团的内幕感兴趣,我在这里写了:

在与代表的引擎盖下

  • Step2应该不是对委托的弱引用?如果我是对的,请编辑它.顺便说一句,你可以使它成为可选值.那将更加迅速.弱var委托:FooTwoViewControllerDelegate?PS:代表应该是保留圈的弱者,孩子应该保持对父母的强烈参考 (23认同)
  • 你需要声明这样的协议,以便为委托协议FooTwoViewControllerDelegate提供弱引用:class {} (4认同)
  • @Shial - 实际上看起来有点复杂.只有非结构和枚举的类才需要`weak`.如果委托将成为结构或枚举,那么您不必担心保留周期.但是,委托它是一个类(这在很多情况下都是如此,因为它通常是一个ViewController),那么你需要`weak`但是你需要将你的协议声明为一个类.这里有更多信息http://stackoverflow.com/a/34566876/296446 (2认同)

Sur*_*gch 90

代表总是把我弄糊涂,直到我意识到委托只是一个为另一个班做一些工作的班级.这就像让别人在那里做你不想做的所有肮脏的工作.

我写了一个小故事来说明这一点.如果你愿意,可以在游乐场阅读.

很久以前...

// 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.
Run Code Online (Sandbox Code Playgroud)

在审查中,制作和使用委托模式有三个关键部分.

  1. 定义工人需要做什么的协议
  2. 具有委托变量的boss类,它用于告诉worker类要做什么
  3. 采用协议并执行所需操作的工作者类

现实生活

与上面的Bossy Big Brother故事相比,代表们经常用于以下实际应用:

  1. 沟通:一个班级需要将一些信息发送到另一个班级.
  2. 自定义:一个类想要允许另一个类来自定义它.

最重要的是,除了委托类符合所需的协议之外,这些类不需要事先了解彼此.

我强烈建议阅读以下两篇文章.他们帮助我了解代表甚至比文档更好.

再说一遍

引用他们不拥有的其他类的代理应该使用该weak关键字来避免强引用周期.有关详细信息,请参阅此答案.

  • 最后有人可以用常识解释协议和委托!谢啦! (3认同)

Ada*_*dam 71

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

class MyClass: NSUserNotificationCenterDelegate
Run Code Online (Sandbox Code Playgroud)

实现将如下所示:

// 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
}
Run Code Online (Sandbox Code Playgroud)

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

NSUserNotificationCenter.defaultUserNotificationCenter().delegate = self;
Run Code Online (Sandbox Code Playgroud)


Shi*_*ial 45

我对@MakeAppPie的帖子进行了一些更正

首先,当您创建委托协议时,它应该符合类协议.如下例所示.

protocol ProtocolDelegate: class {
    func myMethod(controller:ViewController, text:String)
}
Run Code Online (Sandbox Code Playgroud)

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

class ViewController: UIViewController {
    weak var delegate: ProtocolDelegate?
}
Run Code Online (Sandbox Code Playgroud)

最后,您是安全的,因为您的协议是可选值.这意味着它的"nil"消息不会发送到此属性.它类似于respondToselectorobjC中的条件语句,但是在这里你拥有一行:

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

上面你有一个obj-C示例,下面你有Swift示例,它看起来如何.

delegate?.myMethod(self, text:"your Text")
Run Code Online (Sandbox Code Playgroud)


See*_*ode 31

这是我放在一起的要点.我想知道同样的事情,这有助于提高我的理解力.在Xcode Playground中打开它,看看发生了什么.

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()
Run Code Online (Sandbox Code Playgroud)


Man*_*ngh 13

在SWIFT代表2

我用Delegate的例子解释了两个viewControllers.在这种情况下,SecondVC Object将数据发送回第一个View Controller.

具有协议声明的类

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("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)
    }

}
Run Code Online (Sandbox Code Playgroud)

在第一个ViewController协议符合这里完成:

class ViewController: UIViewController, getDataDelegate
Run Code Online (Sandbox Code Playgroud)

First View Controller中的协议方法定义(ViewController)

func getDataFromAnotherVC(temp : String)
{
  // dataString from SecondVC
   lblForData.text = dataString
}
Run Code Online (Sandbox Code Playgroud)

从First View Controller(ViewController)推送SecondVC期间

let objectPush = SecondVC()
objectPush.delegateCustom = self
self.navigationController.pushViewController(objectPush, animated: true)
Run Code Online (Sandbox Code Playgroud)


Eka*_*m E 6

头等舱:

protocol NetworkServiceDelegate: class {

    func didCompleteRequest(result: String)
}


class NetworkService: NSObject {

    weak var delegate: NetworkServiceDelegate?

    func fetchDataFromURL(url : String) {
        delegate?.didCompleteRequest(url)
    }
}
Run Code Online (Sandbox Code Playgroud)

第二类:

class ViewController: UIViewController, NetworkServiceDelegate {

    let network = NetworkService()

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



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


}
Run Code Online (Sandbox Code Playgroud)