Created
August 1, 2015 00:12
-
-
Save austinzheng/db58036c4eb825e63e88 to your computer and use it in GitHub Desktop.
A simple example of setting up a delegate in Swift.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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...") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Click here for set custom delegate and protocol method