Что я хочу: когда поле становится первым отвечающим, курсор должен быть помещен в конец текста (последнее слово), не выделяя весь текст.
Вот код, который создает мое текстовое поле:
Код: Выделить всё
public func makeTextField() -> UITextField {
let textField = UITextField()
textField.autocorrectionType = .no
textField.setContentCompressionResistancePriority(.required, for: .horizontal)
textField.setContentCompressionResistancePriority(.required, for: .vertical)
if #available(iOS 13.0, *) {
textField.smartInsertDeleteType = .no
}
textField.smartQuotesType = .no
textField.smartDashesType = .no
textField.autocapitalizationType = .none
textField.contentMode = .scaleToFill
if let font = attributes[.font] as? UIFont {
textField.font = font
}
if let color = attributes[.foregroundColor] as? UIColor {
textField.textColor = color
}
// Truncate long text at the head
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byTruncatingHead
textField.defaultTextAttributes[.paragraphStyle] = paragraphStyle
textField.delegate = self
textField.backgroundColor = .clear
textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
return textField
}
- Шаги воспроизведения (минимальные):
Установите длинную строку (достаточно длинную, чтобы ее можно было обрезать) как textField.text.
Отобразите поле и коснитесь его, чтобы перейти к фокусу.
Обратите внимание, что весь текст выделяется, а не помещается курсор в конце.
Весь текст выделяется при фокусировке на поле, если текст длинный.
Принудительно поставить курсор в конец в textFieldDidBeginEditing:
Код: Выделить всё
func textFieldDidBeginEditing(_ textField: UITextField) {
let end = textField.endOfDocument
textField.selectedTextRange = textField.textRange(from: end, to: end)
}
Код: Выделить всё
func textFieldDidBeginEditing(_ textField: UITextField) {
DispatchQueue.main.async {
let end = textField.endOfDocument
textField.selectedTextRange = textField.textRange(from: end, to: end)
}
}
Подробнее здесь: https://stackoverflow.com/questions/798 ... o-keep-the
Мобильная версия