Skip to content

Instantly share code, notes, and snippets.

@austinzheng
Created August 1, 2015 00:12
Show Gist options
  • Save austinzheng/db58036c4eb825e63e88 to your computer and use it in GitHub Desktop.
Save austinzheng/db58036c4eb825e63e88 to your computer and use it in GitHub Desktop.
A simple example of setting up a delegate in Swift.
//
// ExampleCode.swift
//
import UIKit
// MARK: - Protocol
protocol SearchQueryProviderProtocol : class { // 'class' means only class types can implement it
func searchQueryData() -> String
}
// MARK: - Table view controller
class MyTableViewController : UITableViewController {
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Try to get a cell
let cell : MyTableViewCell
if let theCell = tableView.dequeueReusableCellWithIdentifier(MyTableViewCell.reuseIdentifier) as? MyTableViewCell {
cell = theCell
} else {
cell = MyTableViewCell()
}
cell.bind(self, title: "This is cell # \(indexPath.row) in the table view")
return cell
}
// Other table view delegate/data source methods
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
}
extension MyTableViewController : SearchQueryProviderProtocol {
func searchQueryData() -> String {
// TODO: actual implementation...
return "hello world"
}
}
// MARK - Cell
class MyTableViewCell : UITableViewCell {
weak var delegate : SearchQueryProviderProtocol?
static let reuseIdentifier = "MyTableViewCell"
func bind(delegate: SearchQueryProviderProtocol, title: String) {
self.delegate = delegate
textLabel?.text = title
}
func doSomethingWhenTapped() {
// TODO: actually set up the cell so this method is called when tapped
if let parentSearchData = delegate?.searchQueryData() {
// TODO: do something with your data...
} else {
println("Something is wrong, this cell's delegate wasn't set...")
}
}
}
@User2004
Copy link

User2004 commented Jan 3, 2019

Click here for set custom delegate and protocol method

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment