【发布时间】:2018-04-22 11:12:11
【问题描述】:
我正在尝试寻找一种方法来避免键盘在动态 UITableViews 中不阻塞选定的 UITextField。
我知道这是一个常见问题,对此有很多答案。但是,我找到的答案要么在 Obj-C 中,要么不涉及动态 UITableView。
我的表格视图有自己的 UITableViewCell,所以 UITextFields 连接到它。
另外,我想在输入 UITextField 时刷新单元格。我可以将该信息(我猜是单元格的 IndexPath.row?)传递给 UIViewController 并让它监听更改并应用重新加载单元格方法吗?
这是我的相关代码:
class favCell: UITableViewCell, UITextFieldDelegate {
@IBOutlet weak var deciPadField: UITextField!
@objc func doneClicked(){
updateTotalWorth()
deciPadField.resignFirstResponder()
deciPadField.endEditing(true)
}
func textFieldDidBeginEditing(_ textField: UITextField) {
deciPadField.becomeFirstResponder()
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let currentString: NSString = (textField.text ?? "") as NSString
let newString = currentString.replacingCharacters(in: range, with: string)
return newString.count <= 10
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
updateTotalWorth()
deciPadField.resignFirstResponder()
return true
}
private func textViewDidEndEditing(_ textView: UITextView) {
updateTotalWorth()
deciPadField.endEditing(true)
}
}
更新:
如果我可以从 UITableViewCell 访问我的 ViewControllers 视图,下面的代码就可以解决问题:
func animateTextField(textField: UITextField, up: Bool) {
let movementDistance:CGFloat = -130
let movementDuration: Double = 0.3
var movement:CGFloat = 0
if up {
movement = movementDistance
} else {
movement = -movementDistance
}
UIView.beginAnimations("animateTextField", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(movementDuration)
// Below line giving error, could not find the view. My ListVC.view should be referred to.
self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement)
UIView.commitAnimations()
}
func textFieldDidBeginEditing(textField: UITextField) {
self.animateTextField(textField: textField, up:true)
}
func textFieldDidEndEditing(textField: UITextField) {
self.animateTextField(textField: textField, up:false)
}
谢谢!
【问题讨论】:
-
试试 self.view.endediting()
-
如果你 (A) 继承
UITableViewController,它应该会自动为你处理。如果您(B) 添加UITableView作为UIViewController的子视图,则您必须在显示/隐藏键盘时自己进行调整。你是在做(A)还是(B)? -
我在做 B。我知道 UITableViewController 的差异。
-
好的 - 那么你必须自己处理它。已经有很多例子了……通读这篇文章,看看你是否可以让它工作。如果没有,请返回并发布您尝试使用的代码:stackoverflow.com/questions/1126726/…
标签: ios arrays uitableview keyboard uitextfield