键盘出现时如何调整ScrollView的大小?

时间:2016-12-18 19:53:40

标签: ios swift uiviewcontroller uiscrollview

我尝试创建此帖子功能,允许您插入文本和图像(类似于iOS设备上的Note应用)。但是,当我按下浅灰色区域(它是文本视图字段)时键盘出现时,我无法弄清楚如何移动或调整ScrollView的大小,因此灰色区域会调整大小并添加按钮会在出现时在键盘上方移动。

//  PostViewController.swift
//
//  Created by Martynas on 09/12/2016.
//  Copyright © 2016 Martynas. All rights reserved.
//

import UIKit
import Firebase

class PostViewController: UIViewController, UITextFieldDelegate {

@IBOutlet var ScrollView: UIScrollView!
@IBOutlet var titleTextField: UITextField!
@IBOutlet var contentTextField: UITextView!
@IBOutlet var Menu: UIView!

@IBAction func hideKeyboardWhenSwippedDown(_ sender: Any) {
    contentTextField.endEditing(true)
}

override func viewDidLoad() {
    super.viewDidLoad()

    // Hide keyboard when...
    self.hideKeyboardWhenTappedAround() // ...press anywhere outside the keyboard

    self.titleTextField.delegate = self
    self.contentTextField.delegate = self

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func sendTapped(_ sender: Any) {

    if let uid = FIRAuth.auth()?.currentUser?.uid {
        if let title = titleTextField.text {
            if let content = contentTextField.text {
                let postObject: Dictionary<String, Any> = [
                    "uid": uid,
                    "title": title,
                    "content": content
                ]

                FIRDatabase.database().reference().child("posts").childByAutoId().setValue(postObject)

            }
        }
    }
}

@IBAction func addTapped(_ sender: Any) {

}

func textFieldDidBeginEditing(_ textField: UITextField) {
    if textField == contentTextField {
        ScrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
    } else {
        return
    }

}

func textFieldDidEndEditing(_ textField: UITextField) {
    if textField == contentTextField {
        ScrollView.setContentOffset(CGPoint(x: 0, y: 250), animated: true)
    } else {
        return
    }
}

// Hide keyboard when user presses 'return' key on the keyboard...
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    titleTextField.resignFirstResponder()
    return true
    }
}

这是控制器视图:

Controller View

1 个答案:

答案 0 :(得分:0)

您需要收听keyboardDidShow/Hide通知并相应地调整滚动视图的高度。 keyboardDidShow通知userInfo包含键盘的框架,因此包含高度。

假设您的滚动视图在超级视图的底部有一个约束,您可以将其设为IBOutlet并将其设置为键盘高度的常量,并在键盘显示和隐藏通知时返回0分别被解雇了。