简体   繁体   中英

iOS: UIView origin y not changing on iOS 9

I'm trying to set my self.mainView.frame.origin.y when the keyboard is displaying. It works fine on iOS 11 but not in iOS 9 .

This is my code:

    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        print("=== textFieldShouldBeginEditing 1 \(self.mainView.frame.origin.y) ")
        self.mainView.frame.origin.y -= 150
        self.mainView.setNeedsLayout()
        self.mainView.layoutIfNeeded()
        print("=== textFieldShouldBeginEditing 2 \(self.mainView.frame.origin.y) ")
        return true
    }



    internal func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        print("=== textFieldShouldReturn 1 \(self.mainView.frame.origin.y) ")
        self.mainView.frame.origin.y = self.normalMainViewOriginY
        textField.endEditing(true)
        print("=== textFieldShouldReturn 2 \(self.mainView.frame.origin.y) ")
        return true
    }

In the viewDidLoad() :

self.normalMainViewOriginY = self.mainView.frame.origin.y

I tested also the same think using NSNotification but I'm getting the same problem in iOS 9

Those are the prints output:

iOS 9:

=== normalMainViewOriginY: 243.0 (from viewDidLoad() )

=== textFieldShouldBeginEditing 1: 208.5

=== textFieldShouldBeginEditing 2: 208.5

=== textFieldShouldReturn 1: 208.5

=== textFieldShouldReturn 2: 243.0

iOS 11:

=== normalMainViewOriginY: 243.0 (from viewDidLoad() )

=== textFieldShouldBeginEditing 1: 208.5

=== textFieldShouldBeginEditing 2: 58.5

=== textFieldShouldReturn 1: 58.5

=== textFieldShouldReturn 2: 243.0

The problem is that changing frames doesn't affect the underlining layout constraints , so try constraints it won't fail , say you have the top constraint of mainView as mainViewTopCon

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    print("=== textFieldShouldBeginEditing 1 \(self.mainView.frame.origin.y) ")
    self.mainViewTopCon.constant -= 150
    self.mainView.layoutIfNeeded()
    print("=== textFieldShouldBeginEditing 2 \(self.mainView.frame.origin.y) ")
    return true
}

internal func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    print("=== textFieldShouldReturn 1 \(self.mainView.frame.origin.y) ")
    self.mainViewTopCon.constant = 0 // or value in IB that you set initally 
    self.mainView.layoutIfNeeded()
    textField.endEditing(true)
    print("=== textFieldShouldReturn 2 \(self.mainView.frame.origin.y) ")
    return true
}

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