Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How can I create a delegate from scratch in Swift? As an example, let's say I want to scroll to the bottom of a tableView every time the keyboard is opened (UITextFieldDelegate). Where do I begin implementing this? The challenge is to execute a method in another class (in this case, view controller). Note: I searched around and did not find a repeat question for the Swift language.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
194 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your question somewhat vague, but I think the word you are looking for is "protocol", exhaustively explained in Apple's docs:

The following example defines a protocol with a single instance method requirement:

protocol RandomNumberGenerator {
    func random() -> Double
}

Somewhere else you create a class that implements the required method:

class LinearCongruentialGenerator: RandomNumberGenerator {
    var lastRandom = 42.0
    let m = 139968.0
    let a = 3877.0
    let c = 29573.0

    func random() -> Double {
        lastRandom = ((lastRandom * a + c) % m)
        return lastRandom / m
    }
}

And somewhere else you store / use the protocol, calling the method defined on the delegate (that implements the protocol).

class Dice {
    let sides: Int
    let generator: RandomNumberGenerator // delegate object that implements the protocol

    init(sides: Int, generator: RandomNumberGenerator) {
        self.sides = sides
        self.generator = generator
    }

    func roll() -> Int {
        return Int(generator.random() * Double(sides)) + 1
    }
}

As to where you do this, it's the same as Obj-c. Swift makes it easier as it does not require you to import header files, so you can either put it in the file of the client (the class that uses it), or in it's own file. Per above, you would declare and implement the protocol method(s) in the class that will become the delegate instance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...