如何使用 Swift 选择 UITextField 中的所有文本 [英] How to select all text in a UITextField using Swift

查看:36
本文介绍了如何使用 Swift 选择 UITextField 中的所有文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码,但由于某种原因它不起作用.有什么想法吗?

I'm using below code, but for some reason it's not working. Any idea?

textField.text = "Hello"

textField.becomeFirstResponder()

textField.selectedTextRange = self.textField.textRangeFromPosition(self.textField.beginningOfDocument, toPosition: self.textField.endOfDocument)

这是我得到的:

推荐答案

其他答案都不适合我.原来我需要把我的代码放在 viewDidAppear 而不是 viewDidLoad:

None of the other answers worked for me. It turned out that I needed to place my code in viewDidAppear instead of viewDidLoad:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    
    textField.becomeFirstResponder()
    textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: textField.endOfDocument) 
}

还有一些其他方法可以选择其他人可能认为有帮助的所有文本:

There are also some additional ways to select all text that others may find helpful:

// Select all without showing menu (Cut, Copy, etc)
textField.selectAll(nil)

// Select all and show menu
textField.selectAll(self)

这篇关于如何使用 Swift 选择 UITextField 中的所有文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆