标题真的说明了一切。我尝试过以下方式从viewDidLoad中选择文字:
override func viewDidLoad() {
...
guessField.text = " "
guessField.becomeFirstResponder()
guessField.selectedTextRange = guessField.textRange(from: guessField.beginningOfDocument, to: guessField.position(from: guessField.endOfDocument, offset: -3)!)
}
但是,这不起作用;光标刚出现在最后一个位置。有没有人有想法解决这个问题?
答案 0 :(得分:1)
一旦您的视图加载,看起来需要一些时间。尝试以下解决方案:
首先在你的课程中添加以下功能:
func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) {
DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
completion()
}
}
然后在viewWillAppear
方法中使用它,如下所示:
override func viewWillAppear(_ animated: Bool) {
delayWithSeconds(1) {
self.guessField.text = " "
self.guessField.becomeFirstResponder()
self.guessField.selectedTextRange = self.guessField.textRange(from: self.guessField.beginningOfDocument, to: self.guessField.position(from: self.guessField.endOfDocument, offset: -3)!)
}
}
我刚把它推迟了1秒。