Swift 实现修改光标位置(任意或指定)
2018-12-10 本文已影响0人
FanChason
-
看效果
UITextField.gif -
原理:主要就是原生方法调用,较简单。也就是指定
selectedTextRange
-
上代码:创建一个UITextField的扩展
UITextField+Extension.swift
//
// UITextField+Extension.swift
//
import UIKit
extension UITextField {
func selectedRange() -> NSRange {
let beginning = self.beginningOfDocument
let selectedRange = self.selectedTextRange
let selectionStart = selectedRange!.start
let selectionEnd = selectedRange!.end
let location: NSInteger = self.offset(from: beginning, to: selectionStart)
let length: NSInteger = self.offset(from: selectionStart, to: selectionEnd)
return NSRange.init(location: location, length: length)
}
func setSelectedRange(range: NSRange) {
let beginning = self.beginningOfDocument
let startPosition = self.position(from: beginning, offset: range.location)!
let endPosition = self.position(from: beginning, offset: range.location + range.length)!
let selectionRange = self.textRange(from: startPosition, to: endPosition)
self.selectedTextRange = selectionRange
}
}
- 使用
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
if textField.text!.count > 0 && !(textField.text!.contains(" cm")) {
if textField == self.dadHTextField {
let range = self.dadHTextField.selectedRange()
self.dadHTextField.text!.append(" cm")
self.dadHTextField.setSelectedRange(range: range)
} else {
self.motherHTextField.text!.append(" cm")
}
}
}
return true
}