我有一个自定义单元格,在自定义单元格中我有一个textField,我想知道如何从customCell类中创建一个协议来调用我的ViewController中的函数。我做了一些代码,但卡住了。
我的问题是,一旦我触摸textField,我想从我的ViewController调用一个函数。
class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, MySearchDelegate {
var search:SearchTableViewCell = SearchTableViewCell()
override func viewDidLoad() {
search.delegate = self
}
}
我的customCell类:
@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)
}
}
答案 0 :(得分:1)
我对swift并不擅长,所以这可能是个错误。您应该在创建单元格时分配单元格委托。
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
}
}
答案 1 :(得分:0)
修改代码以避免强引用周期并符合您的协议:
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)
}
}