iOS:UIView起源在iOS 9上没有变化

时间:2018-04-04 23:36:38

标签: ios swift uiview uikeyboard

我在self.mainView.frame.origin.y显示时尝试设置keyboard。它适用于iOS 11,但不适用于iOS 9

这是我的代码:

    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
    }

viewDidLoad()

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

我也使用NSNotification对同样的问题进行了测试,但我在iOS 9

中遇到了同样的问题

这些是打印输出:

iOS 9:

=== normalMainViewOriginY:243.0(来自viewDidLoad()

=== textFieldShouldBeginEditing 1:208.5

=== textFieldShouldBeginEditing 2:208.5

=== textFieldShouldReturn 1:208.5

=== textFieldShouldReturn 2:243.0

iOS 11:

=== normalMainViewOriginY:243.0(来自viewDidLoad()

=== textFieldShouldBeginEditing 1:208.5

=== textFieldShouldBeginEditing 2:58.5

=== textFieldShouldReturn 1:58.5

=== textFieldShouldReturn 2:243.0

1 个答案:

答案 0 :(得分:0)

问题在于更改框架并不会影响下划线布局约束,因此尝试使用它不会失败的约束,比如说你将mainView的顶部约束设为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
}