美文网首页swift
Swift---限制 UITextField 的中文输入长度

Swift---限制 UITextField 的中文输入长度

作者: henu_Larva | 来源:发表于2018-04-16 13:48 被阅读285次
原文链接: 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)
    }
}


相关文章

网友评论

    本文标题:Swift---限制 UITextField 的中文输入长度

    本文链接:https://www.haomeiwen.com/subject/pkfekftx.html