Swift 键盘出现到文本字段移动无法正常工作
Posted
技术标签:
【中文标题】Swift 键盘出现到文本字段移动无法正常工作【英文标题】:Swift keyboard appear to textfield move not working properly 【发布时间】:2018-08-25 13:26:15 【问题描述】:我试图在键盘出现时创建相应的文本字段应该移动到键盘顶部,这里有两件事我需要解决,在编辑时间文本字段到起点时,我还需要在子类中使用下面的代码,因为想要得到由多个其他类文本字段引用。
这里,在我的代码下面
extension UIView
func bindToKeyboard()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
func unbindFromKeyboard()
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
@objc
func keyboardWillChange(notification: NSNotification)
guard let userInfo = notification.userInfo else return
let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double
let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as! UInt
let curFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let targetFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let deltaY = targetFrame.origin.y - curFrame.origin.y
UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations:
self.frame.origin.y += deltaY
)
在 Viewdidload 中
baseview.bindToKeyboard()
文本字段应该返回
func textFieldShouldReturn(_ textField: UITextField) -> Bool
self.baseview.endEditing(true)
return false
【问题讨论】:
【参考方案1】:你可以考虑使用这个框架,它会帮助你很多努力: https://github.com/hackiftekhar/IQKeyboardManager
import IQKeyboardManagerSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
IQKeyboardManager.shared.enable = true
return true
【讨论】:
兄弟,我需要一些代码,这样我才能理解更多......@koingDev【参考方案2】:完美运行。试试这个
// Start Editing The Text Field
func textFieldDidBeginEditing(_ textField: UITextField)
moveTextField(textField, moveDistance: -100, up: true)
// Finish Editing The Text Field
func textFieldDidEndEditing(_ textField: UITextField)
moveTextField(textField, moveDistance: -100, up: false)
// Hide the keyboard when the return key pressed
func textFieldShouldReturn(_ textField: UITextField) -> Bool
textField.resignFirstResponder()
return true
// Move the text field in a pretty animation!
func moveTextField(_ textField: UITextField, moveDistance: Int, up: Bool)
let moveDuration = 0.3
let movement: CGFloat = CGFloat(up ? moveDistance : -moveDistance)
UIView.beginAnimations("animateTextField", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(moveDuration)
self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement)
UIView.commitAnimations()
【讨论】:
以上是关于Swift 键盘出现到文本字段移动无法正常工作的主要内容,如果未能解决你的问题,请参考以下文章
如何在swift3 ios中使用键盘返回键将一个文本字段移动到另一个文本字段