原文链接: http://www.hangge.com/blog/cache/detail_1907.html
//
// ViewController.swift
// Swift_Test
//
// Created by larva on 2018/4/16.
// Copyright © 2018年 larva. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let max_Length:Int = 10
var textField:UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
textField = UITextField()
textField.frame = CGRect(x: 20, y: 100, width: 200, height: 30)
textField.borderStyle = UITextBorderStyle.roundedRect
self.view.addSubview(textField)
}
override func viewDidAppear(_ animated: Bool) {
NotificationCenter.default.addObserver(self, selector: #selector(self.greetingTextFieldChanged), name: NSNotification.Name(rawValue:"UITextFieldTextDidChangeNotification"), object: self.textField)
}
@objc func greetingTextFieldChanged(obj:Notification) {
//非 marketedText 才继续往下处理
guard let _:UITextRange = textField.markedTextRange else {
//记录当前光标的位置,后面需要进行修改
let cursorPostion = textField.offset(from: textField.endOfDocument, to: textField.selectedTextRange!.end)
//判断非中文的正则表达式
let pattern = "[^\\u4E00-\\u9FA5]"
//替换后的字符串(已过滤非中文字符)
var str = textField.text!.pregReplace(pattern: pattern, with: "")
//限制最大输入长度
if str.count > max_Length {
str = String(str.prefix(max_Length))
}
textField.text = str
//让光标停留在正确的位置
let targetPosion = textField.position(from: textField.endOfDocument, offset: cursorPostion)!
textField.selectedTextRange = textField.textRange(from: targetPosion, to: targetPosion)
return
}
}
override func viewDidDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue:"UITextFieldTextDidChangeNotification"), object: self.textField)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
}
extension String {
//使用正则表达式替换
func pregReplace(pattern: String, with: String,
options: NSRegularExpression.Options = []) -> String {
let regex = try! NSRegularExpression(pattern: pattern, options: options)
return regex.stringByReplacingMatches(in: self, options: [],
range: NSMakeRange(0, self.count),
withTemplate: with)
}
}
网友评论