美文网首页
UITextField和UITextView高度计算,只能输入中

UITextField和UITextView高度计算,只能输入中

作者: 九龙 | 来源:发表于2019-01-22 11:32 被阅读6次

    UITextView

    1.准确计算UITextView的高度

    @IBOutlet weak var detailAddressTextView: UITextView!{
            didSet{
                detailAddressTextView.delegate = self
                detailAddressTextView.textContainerInset = .zero
                let padding = detailAddressTextView.textContainer.lineFragmentPadding;
                detailAddressTextView.textContainerInset = UIEdgeInsets(top: 0, left: -padding, bottom: 0, right: -padding)
            }
        }
    
    func calculateHeight(text:String?)-> CGFloat{
            let attr = [NSAttributedString.Key.font: addressTextField.font]
            let width = KScreenWidth - 118
            let maxSize: CGSize = CGSize(width:width, height: CGFloat(MAXFLOAT))
            let option = NSStringDrawingOptions.usesLineFragmentOrigin.rawValue|NSStringDrawingOptions.usesFontLeading.rawValue
            let height = text?.boundingRect(with: (maxSize), options: NSStringDrawingOptions(rawValue: option), attributes: attr as [NSAttributedString.Key : Any], context: nil).size.height ?? 0
            return  (height < 79 ? 79 : height) + 10
        }
    
    extension AddAddressViewController: UITextViewDelegate{
        func textViewDidChange(_ textView: UITextView) {
            textHeightLayout.constant = calculateHeight(text: textView.text)
            self.view.setNeedsLayout()
        }
    }
    
    

    UITextField

    1.准确限制UITextField的输入位数

    nameTextField.addTarget(self, action: #selector(nameTextFieldDidChangeValue), for: .editingChanged)
    @objc func nameTextFieldDidChangeValue(_ sender: UITextField) {
            guard let name = sender.text else{ return }
            if name.count >= 10 {           //名字的位数不能超过11位
                if sender.markedTextRange != nil {
                    return
                }
                sender.text = name.substring(from: 0, to: 9)
            }
        }
    

    2.限制UITextField的只能输入中文

    import UIKit
    
    class ChineseTextField: UITextField {
        override init(frame: CGRect) {
            super.init(frame: frame)
            setupUI()
        }
        
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            setupUI()
        }
        
        func setupUI() {
            NotificationCenter.default.addObserver(self, selector: #selector(textFiledEditChanged(not:)), name: UITextField.textDidChangeNotification, object: nil)
        }
        @objc func textFiledEditChanged(not:Notification) {
            //非markedText才继续往下处理
            guard let _:UITextRange = self.markedTextRange else {
            guard let end = self.selectedTextRange?.end else { return }
                //当前光标的位置
                let cursorPosition = self.offset(from: self.endOfDocument, to: end)
                let pattern = "[^\\u4E00-\\u9FA5]"
                //替换后的字符串(过滤调非中文字符)
                let str = self.text!.pregReplace(pattern: pattern, with: "")
                self.text = str
                
                //让光标停留在正确位置
                guard let targetPostion = self.position(from: self.endOfDocument,
                                                        offset: cursorPosition) else{ return }
                self.selectedTextRange = self.textRange(from: targetPostion,
                                                                  to: targetPostion)
                return
            }
        }
        deinit {
            NotificationCenter.default.removeObserver(self)
        }
    }
    
    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)
        }
    }
    
    

    3.限制UITextField的只能输入数字和英文

    1.定义能输入的字符串
    let ALPHANUM = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
    2.设置代理
    fileNumberTextField.delegate = self
    3.实现代理方法
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            let cs = CharacterSet(charactersIn: ALPHANUM).inverted
            let filtered = string.components(separatedBy: cs).joined(separator: "")
            return string == filtered
        }
    

    2.计算文本高度里面(包含有"\n"换行符)

     //给定宽度,计算文本的高度
    
    static var attr:[NSAttributedString.Key : Any] {
            let paraph = NSMutableParagraphStyle()
            paraph.maximumLineHeight = 24
            paraph.minimumLineHeight = 24
            let attr: [NSAttributedString.Key : Any] = [NSAttributedString.Key.font: UIFont(name: kPingFangSCRegular, size: 16) ?? UIFont.systemFont(ofSize: 16),NSAttributedString.Key.paragraphStyle:paraph,NSAttributedString.Key.foregroundColor:kLoginDarkGrayColor]
            return attr
        }
    
        func calculateWidthWith(width: CGFloat)-> CGFloat {
            //文字最大尺寸
            let maxSize: CGSize = CGSize(width: width, height: CGFloat(MAXFLOAT))
            let options = NSStringDrawingOptions.usesLineFragmentOrigin.rawValue|NSStringDrawingOptions.usesFontLeading.rawValue
            let replaceStr = "\n"
            let contentString = (dialoContent as NSString).replacingOccurrences(of: replaceStr, with: "")
            let count = (dialoContent.count - contentString.count) / replaceStr.count
            let option = NSStringDrawingOptions.init(rawValue:options )
            let dialoContentAtt = NSAttributedString(string: contentString, attributes: MessageNormalCell.attr)
            
            let replaceH = dialoContentAtt.boundingRect(with: maxSize, options: option, context: nil).size.height
            return replaceH + CGFloat(count * 24)
        }
    

    相关文章

      网友评论

          本文标题:UITextField和UITextView高度计算,只能输入中

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