美文网首页
UITextView限制字数与首行问题

UITextView限制字数与首行问题

作者: 费城的二鹏 | 来源:发表于2018-12-19 11:38 被阅读8次
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if type == .mark {
            self.title = "修改个性签名"
            maxLen = 20
            key = "personalSign"
            tips = "个性签名不能为空"
        }
        
        textView.delegate = self
        textView.text = value
        // textView.textContainer.maximumNumberOfLines = 1
        self.automaticallyAdjustsScrollViewInsets = false
        textViewDidChange(textView)
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if text == "\n" {
            return false
        }
        return true
    }
    
    override func viewDidLayoutSubviews() {
        textView.setContentOffset(.zero, animated: false)
    }

    func textViewDidChange(_ textView: UITextView) {
        
        let selectRange = textView.markedTextRange
        
        if let selectRange = selectRange {
            if let _ = textView.position(from: selectRange.start, offset: 0) {
                return
            }
        }
        
        if textView.text.length() > maxLen {
            textView.text = textView.text.sub(0, end: maxLen)
        }
        countLabel.text = "\(textView.text.length())/\(maxLen)"
    }

相关文章

网友评论

      本文标题:UITextView限制字数与首行问题

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