Reputation: 1717
I’ve a custom cell and in the custom cell I have a textField and I would like to know how can I make a protocol from the customCell class to call a function in my ViewController. I have did some code but stuck.
My issue is once I touch the textField I want to call a function from my ViewController.
class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, MySearchDelegate {
var search:SearchTableViewCell = SearchTableViewCell()
override func viewDidLoad() {
search.delegate = self
}
}
My customCell class:
@objc protocol MySearchDelegate{
optional func textFieldTouched()
}
class SearchTableViewCell: UITableViewCell, UITextFieldDelegate {
@IBOutlet weak var searchField: UITextField!
// this is where I declare the protocol
var delegate:MySearchDelegate?
func searchStart(){
delegate?.textFieldTouched!()
}
override func awakeFromNib() {
super.awakeFromNib()
searchField.addTarget(self, action: Selector("searchStart"), forControlEvents: UIControlEvents.ValueChanged)
}
func searchStart(){
delegate?.textFieldTouched()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
Upvotes: 0
Views: 61
Reputation: 1044
I am not good on swift so it might be a mistake. You should assign the cell delegate when you create the cell.
class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, MySearchDelegate {
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
// set the delegate here not in the viewDidLoad
cell.searchDelegate = self
return cell
}
func textFieldTouched(){
//do what you want here
}
}
Upvotes: 1
Reputation: 4176
Altered your code to avoid strong reference cycles and conforming to your protocol:
var search:SearchTableViewCell = SearchTableViewCell()
override func viewDidLoad() {
search.delegate = self
}
func textFieldTouched() {
println("voila")
}
}
protocol MySearchDelegate: class {
func textFieldTouched()
}
class SearchTableViewCell: UITableViewCell, UITextFieldDelegate {
@IBOutlet weak var searchField: UITextField!
// this is where I declare the protocol
weak var delegate:MySearchDelegate?
func searchStart(){
delegate?.textFieldTouched()
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
Upvotes: 0