Swift

Swift 实现修改光标位置(任意或指定)

2018-12-10  本文已影响0人  FanChason
//
//  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
    }
上一篇下一篇

猜你喜欢

热点阅读