becomeFirstResponder works in viewDidAppear but doesn't work in viewDidLoad

后端 未结 7 1069
傲寒
傲寒 2021-02-13 04:49

My Application has a modal view controller, including a search bar. When the view comes up, I want the search bar to be focused. I tried [self.searchBar becomeFirstRespond

7条回答
  •  生来不讨喜
    2021-02-13 05:00

    You should call in viewDidLayoutSubviews(), the code below set textField becomeFirstResponder only at the first time view layout subviews, and it should be.

    var isFirstLayout: Bool = true
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        if isFirstLayout {
            defer { isFirstLayout = false }
            textField.becomeFirstResponder()
        }
    }
    

提交回复
热议问题