首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在UIView中调用UITextFieldDelegate

如何在UIView中调用UITextFieldDelegate
EN

Stack Overflow用户
提问于 2018-03-16 17:59:55
回答 1查看 539关注 0票数 0

当我在视图中单击一个文本字段时,我无法调用UITextField的委托方法。func textFieldShouldReturn(_ textField: UITextField) -> Bool有什么想法吗?

代码语言:javascript
复制
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
}
}
EN

回答 1

Stack Overflow用户

发布于 2018-03-16 18:07:51

当你点击textfield时,textfield就变成了第一个响应器,下面的委托方法调用:-

代码语言:javascript
复制
func textFieldDidBeginEditing(_ textField: UITextField)

当用户按下return按钮时调用textFieldShouldReturn方法

官方链接:- https://developer.apple.com/documentation/uikit/uitextfielddelegate/1619590-textfielddidbeginediting

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49317843

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档