如何在swift中为uitableview提供的文本字段更改事件?
问题描述:
我有一个UITableView每行都有一个文本字段。当用户在文本字段上键入内容时,我想触发textFieldDidChange或其他任何内容。基本上当文本字段发生变化时,我想要计算一些东西,我该怎么做呢?我正在使用swift。如何在swift中为uitableview提供的文本字段更改事件?
这里是我的代码部分:
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(tableView == self.seatsDropDownTblView){
return seatsList!.count
}else{
return priceList!.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == self.seatsDropDownTblView {
let seats_cell = tableView.dequeueReusableCell(withIdentifier: "SeatsCell", for: indexPath) as! SeatsCell
seats_cell.seatsCountLbl.text = self.seatsList?[indexPath.row]
seats_cell.selectionStyle = .none
return seats_cell
}else {
let price_cell = tableView.dequeueReusableCell(withIdentifier: "AddPriceCell", for: indexPath) as! AddPriceCell
price_cell.txtPrice.text = priceList?[indexPath.row].Price
price_cell.dropOffPointLbl.text = priceList?[indexPath.row].DropPoint
self.indexPathArray.append(indexPath as NSIndexPath)
price_cell.txtPrice.tag = indexPath.row
//Delegates
price_cell.txtPrice.delegate = self
//Assign Delegates
price_cell.txtPrice.delegate = self
price_cell.selectionStyle = .none
return price_cell
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == self.seatsDropDownTblView {
//let seats_cell = tableView.dequeueReusableCell(withIdentifier: "SeatsCell", for: indexPath) as! SeatsCell
//seats_cell.selectionStyle = .none
self.selectedSeat = (self.seatsList?[indexPath.row])!
self.selectedSeatLbl.text = self.selectedSeat
self.seatsDropDownView.isHidden = true
isDropDownFalls = true
self.dropDownBtnImg.image = UIImage(named:"drop_down")
}else {
let cell = tableView.cellForRow(at: indexPath) as! AddPriceCell
cell.selectionStyle = .none
}
}
func textFieldDidChange(_ textField: UITextField) {
NSLog("Event Triggered")
}
这代表不会被触发。我也导入了UITextFieldDelegate协议。任何建议?
答
您必须区分动作和委托方法。代表方法的正确签名是textField(_:, shouldChangeCharactersIn range:, replacementString:)。所以,你必须实现它:
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
NSLog("Event Triggered")
return true
}
你可以用你的方法textFieldDidChange(_:)
的操作方法。要注册使用它:
price_cell.txtPrice.addTarget(self,
action: #selector(textFieldDidChange(_:)),
for: .valueChanged)
答
没有方法在UITextFieldDelegate
textFieldDidChange
为UITextField。这就是为什么它没有得到你的要求。您需要实施UITextFieldDelegate
中的一种可用方法。
我想textFieldDidEndEditing
是你可能想要实现的。 要检查UITextFieldDelegate
中的所有方法,请在XCode中通过命令+点击UITextFieldDelegate
。
其中textfield是你在cellForRowAt中添加'textFieldDidChange' –
为什么不在'AddPriceCell'单元类中添加委托方法? – Akhilrajtr
YOUR_TEXTFILED.addTarget(self,action:#selector(textChanged(_ :)),for:.valueChanged) –