当我在视图中单击一个文本字段时,我无法调用UITextField的委托方法。func textFieldShouldReturn(_ textField: UITextField) -> Bool有什么想法吗?
import UIKit
class CustomUIViewScreen: UIView {
override func awakeFromNib() {
...
textField.delegate = self
}
override func didMoveToWindow() {
if (self.window != nil) {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: .UIKeyboardWillHide, object: nil)
}
}
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.frame.origin.y == 0{
self.frame.origin.y -= keyboardSize.height - 60
}
UIView.animate(withDuration: 0.2) {
self.layoutIfNeeded()
}
}
}
@objc func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let info = notification.userInfo! as NSDictionary
let animationDuration = info.object(forKey: UIKeyboardAnimationDurationUserInfoKey)
UIView.animate(withDuration: animationDuration as! TimeInterval) {
if self.frame.origin.y != 0 {
self.frame.origin.y += keyboardSize.height
self.layoutIfNeeded()
}
}
}
}
}
extension CustomUIViewScreen : UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let nextTag = textField.tag + 1
let nextResponder = textField.superview?.viewWithTag(nextTag) as UIResponder!
if (nextResponder != nil) {
nextResponder?.becomeFirstResponder()
} else {
textField.resignFirstResponder()
}
return false
}
}发布于 2018-03-16 18:07:51
当你点击textfield时,textfield就变成了第一个响应器,下面的委托方法调用:-
func textFieldDidBeginEditing(_ textField: UITextField)当用户按下return按钮时调用textFieldShouldReturn方法
官方链接:- https://developer.apple.com/documentation/uikit/uitextfielddelegate/1619590-textfielddidbeginediting
https://stackoverflow.com/questions/49317843
复制相似问题