xcode 当键盘出现 Swift 时,使用文本字段和按钮向上移动视图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50325019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
moving View up with textfield and Button when keyboard appear Swift
提问by William Loke
I know there are a few posted questions on this topic, but none of them worked. I have a tableview and under it there's a UIView that contains a textfield and button. When my keyboard appears, it covers the whole UIView, making me unable to click "Send". The image to show how my app looks like :
我知道有一些关于此主题的已发布问题,但没有一个有效。我有一个 tableview,在它下面有一个 UIView,其中包含一个文本字段和按钮。当我的键盘出现时,它覆盖了整个 UIView,使我无法单击“发送”。显示我的应用程序外观的图像:
at the moment, my codes are:
目前,我的代码是:
override func viewDidLoad() {
super.viewDidLoad()
inputTextField.delegate = self
inputTextField.layer.cornerRadius = 5
inputTextField.clipsToBounds = true
sendButton.layer.cornerRadius = 5
sendButton.clipsToBounds = true
self.tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "TableViewCell")
loadMsg()
self.hideKeyboardWhenTappedAround()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
inputTextField.becomeFirstResponder()
}
How should I move the UIView up along with the textfield and button that is contained by the UIView when my keyboard appears?
当我的键盘出现时,我应该如何将 UIView 与 UIView 包含的文本字段和按钮一起向上移动?
回答by iParesh
Here is solution, Create bottom layout constraint reference of send button view
这是解决方案,创建发送按钮视图的底部布局约束参考
@IBOutlet weak var bottomConstraint: NSLayoutConstraint!
@IBOutlet weak var sendbuttonView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self)
}
@objc func handleKeyboardNotification(_ notification: Notification) {
if let userInfo = notification.userInfo {
let keyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue
let isKeyboardShowing = notification.name == NSNotification.Name.UIKeyboardWillShow
bottomConstraint?.constant = isKeyboardShowing ? -keyboardFrame!.height : 0
UIView.animate(withDuration: 0.5, animations: { () -> Void in
self.view.layoutIfNeeded()
})
}
}
回答by aBilal17
Just add thislibrary into your project using POD and thats it. It will automatically do it. You have not to do anything else.
只需使用 POD将此库添加到您的项目中即可。它会自动做到这一点。你不必做任何其他事情。
Add pod like that
像这样添加吊舱
pod 'IQKeyboardManagerSwift'
In AppDelegate.swift, just import IQKeyboardManagerSwift framework and enable IQKeyboardManager.
在 AppDelegate.swift 中,只需导入 IQKeyboardManagerSwift 框架并启用 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
}
}
For reference please have a look on this url, https://github.com/hackiftekhar/IQKeyboardManager
作为参考,请查看此 url,https://github.com/hackiftekhar/IQKeyboardManager
回答by IOS Singh
Swift 4.2
斯威夫特 4.2
in viewDidLoad()
在 viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboard(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboard(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboard(notification:)), name:UIResponder.keyboardWillChangeFrameNotification, object: nil)
and Method
和方法
@objc func keyboard(notification:Notification) {
guard let keyboardReact = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else{
return
}
if notification.name == UIResponder.keyboardWillShowNotification || notification.name == UIResponder.keyboardWillChangeFrameNotification {
self.view.frame.origin.y = -keyboardReact.height
}else{
self.view.frame.origin.y = 0
}
}
回答by Abdelahad Darwish
You can do it by move View up with constraint
here actionBarPaddingBottomConstranit
is Constraint connect to your Input View Bottom
constraint Check image
您可以通过将视图向上移动来实现,constraint
这里actionBarPaddingBottomConstranit
是约束连接到您的输入视图Bottom
约束检查图像
In ViewDidload :
在 ViewDidload 中:
override func viewDidLoad() {
super.viewDidLoad()
self.keybordControl()
}
Extension :
延期 :
extension ViewController{
func keybordControl(){
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
@objc func keyboardWillShow(notification: Notification) {
self.keyboardControl(notification, isShowing: true)
}
@objc func keyboardWillHide(notification: Notification) {
self.keyboardControl(notification, isShowing: false)
}
private func keyboardControl(_ notification: Notification, isShowing: Bool) {
/* Handle the Keyboard property of Default, Text*/
var userInfo = notification.userInfo!
let keyboardRect = (userInfo[UIKeyboardFrameEndUserInfoKey]! as AnyObject).cgRectValue
let curve = (userInfo[UIKeyboardAnimationCurveUserInfoKey]! as AnyObject).uint32Value
let convertedFrame = self.view.convert(keyboardRect!, from: nil)
let heightOffset = self.view.bounds.size.height - convertedFrame.origin.y
let options = UIViewAnimationOptions(rawValue: UInt(curve!) << 16 | UIViewAnimationOptions.beginFromCurrentState.rawValue)
let duration = (userInfo[UIKeyboardAnimationDurationUserInfoKey]! as AnyObject).doubleValue
var pureheightOffset : CGFloat = -heightOffset
if isShowing {
if #available(iOS 11.0, *) {
pureheightOffset = pureheightOffset + view.safeAreaInsets.bottom
}
}
self.actionBarPaddingBottomConstranit?.update(offset:pureheightOffset)
UIView.animate(
withDuration: duration!,
delay: 0,
options: options,
animations: {
self.view.layoutIfNeeded()
},
completion: { bool in
})
}
}
回答by Musavir Parambil
Try the following code
试试下面的代码
//Declare a delegate, assign your textField to the delegate and then include these methods
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
[self.view endEditing:YES];
return YES;
}
- (void)keyboardDidShow:(NSNotification *)notification
{
// Assign new frame to your view
[self.view setFrame:CGRectMake(0,-110,320,460)]; //here taken -110 for example i.e. your view will be scrolled to -110. change its value according to your requirement.
}
-(void)keyboardDidHide:(NSNotification *)notification
{
[self.view setFrame:CGRectMake(0,0,320,460)];
}
回答by iVarun
Call below method in ViewDidLoad:
在 ViewDidLoad 中调用以下方法:
func keyboardSettings(){
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardNotification(notification:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:))))
let swipeDown = UISwipeGestureRecognizer(target: self.view , action : #selector(UIView.endEditing(_:)))
swipeDown.direction = .down
self.view.addGestureRecognizer(swipeDown)
}
Then add below method for keyboard configuration:
然后添加以下键盘配置方法:
@objc func keyboardNotification(notification: NSNotification) {
if let userInfo = notification.userInfo {
if let endFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue{
if let duration:TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue{
let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber
let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIViewAnimationOptions.curveEaseInOut.rawValue
let animationCurve:UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw)
if (endFrame.origin.y) >= UIScreen.main.bounds.size.height {
self.const_ViewMessage_Bottom?.constant = 0.0
} else {
self.const_ViewMessage_Bottom?.constant = endFrame.size.height
}
UIView.animate(withDuration: duration,
delay: TimeInterval(0),
options: animationCurve,
animations: { self.view.layoutIfNeeded() },
completion: nil)
}
}
}
}
self.const_ViewMessage_Bottom
is bottom constraint of UIView with textfield.
self.const_ViewMessage_Bottom
是带有文本字段的 UIView 的底部约束。
回答by G?khan Say?lgan
with one extension to use in all ViewControllers. Create a empty swift file copy this code inside file
在所有 ViewController 中使用一个扩展。创建一个空的 swift 文件将此代码复制到文件中
import UIKit
extension UIViewController {
func keyboardCheck() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y == 0 {
self.view.frame.origin.y -= keyboardSize.height
}
}
}
@objc func keyboardWillHide(notification: NSNotification) {
if self.view.frame.origin.y != 0 {
self.view.frame.origin.y = 0
}
}
}
Then call the function inside ViewDidLoad Usage:
然后调用ViewDidLoad里面的函数用法:
override func viewDidLoad() {
super.viewDidLoad()
self.keyboardCheck()
}