简体   繁体   中英

How would I push a view upwards when keyboard is shown when user touches a text view?

I have a VC in which I have 3 elements (2 text fields at the top and 1 text view at the bottom). The text view at the bottom is unfortunately hidden when the keyboard appears. I'd like to push my view upwards when the user taps or touches the text view at the bottom, but NOT when they touch the 2 text fields at the top. I've found a solution to push my view upwards but it work when any of the 3 elements are touched, thus hiding the 2 text fields at the top. How can I apply the code below to work only when users touch the text view?

@IBOutlet weak var firstTopTextField: UITextField!
@IBOutlet weak var secondTopTextField: UITextField!
@IBOutlet weak var bottomTextView: UITextView!

override func viewDidLoad() {
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil);
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil);

}

func keyboardWillShow(sender: NSNotification) {
    self.view.frame.origin.y -= 160
}

func keyboardWillHide(sender: NSNotification) {
    self.view.frame.origin.y += 160
}

You can use the UITextField/View delegate to get notified when a text field begins editing. Eg

- (void)textFielDidBeginEditing:(UITextField *)textField
{
    // Push screen up
}

It's worth noting that if the user has a external keyboard attached the on screen keyboard will not show but the screen will still be pushed up. You can avoid this by having a BOOL (or should I say var now) that tells you whether the keyboard is showing.

Eg

var isShown = false

func keyboardWillShow(sender:NSNotification) {
    isShown = true
}

func keyboardWillHide(sender:NSNotification) {
    isShown = false
}

func textFieldDidBeginEditing(textField:UITextField) {
    if isShown == true {
        // Push screen up.
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM