Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

ios - How to create delegates in Swift?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...