使用Swift选择UITextField中的所有文本

时间:2014-08-19 13:29:42

标签: swift uitextfield

如何以编程方式选择Swift文本字段中的所有文本?

var textField:UITextField = UITextField()
textField.frame = CGRectMake(2, 25, 200, 20)
textField.text = "hello"
textField.font = UIFont(name: "Verdana", size: 12)
textField.textColor = UIColor.blackColor()
textField.backgroundColor = UIColor.whiteColor()

或者至少让文字立即可编辑?

由于

安德鲁

4 个答案:

答案 0 :(得分:32)

它的工作方式与Objective-C相同:

textField.becomeFirstResponder()

textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: textField.endOfDocument)

答案 1 :(得分:12)

textField.becomeFirstResponder()
textField.selectAll(nil)

答案 2 :(得分:2)

尝试一下:

确保您遵守UITextFieldDelegate并实施:

func textFieldDidBeginEditing(_ textField: UITextField) {
        //highlights all text
        textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: textField.endOfDocument)
}

答案 3 :(得分:1)

如果需要使用它来处理SwiftUI TextField,则可以使用Introspect

import Introspect

private class TextFieldObserver: NSObject {
    @objc
    func textFieldDidBeginEditing(_ textField: UITextField) {
        textField.selectAll(nil)
    }
}

struct ContentView {
    private let textFieldObserver = TextFieldObserver()
    var body: some View {
        TextField(...)
            .introspectTextField { textField in
                textField.addTarget(
                    self.textFieldObserver,
                    action: #selector(TextFieldObserver.textFieldDidBeginEditing),
                    for: .editingDidBegin
                )
            }
    }
}

请注意,您不应覆盖textField.delegate,因为SwiftUI会设置自己的委托,该委托应该对您隐藏。