效果图
适配用的 SnapKit
使用介绍: http://www.hangge.com/blog/cache/detail_1097.html
1 private func creationTextView(){ 2 3 let viewBg = UIView() 4 self.view.addSubview(viewBg) 5 viewBg.frame = CGRect(x:20, y:84, SCREEN_WITH - 40, height:220) 6 viewBg.backgroundColor = UIColor.white 7 viewBg.layer.borderColor = UIColor.init(red: 208/255.0, green: 208/255.0, blue: 208/255.0, alpha: 1).cgColor 8 viewBg.layer.borderWidth = 1 9 viewBg.layer.cornerRadius = 3 10 viewBg.clipsToBounds = true 11 12 13 let textView = UITextView() 14 viewBg.addSubview(textView) 15 16 textView.delegate = self 17 textView.backgroundColor = UIColor.white 18 textView.tintColor = UIColor.red 19 textView.font = UIFont.systemFont(ofSize: 18) 20 textView.textAlignment = .left 21 textView.contentInset = UIEdgeInsetsMake(0, 0, 60, 0) 22 //可以滚动 23 textView.isScrollEnabled = true 24 //自适应高度 25 textView.autoresizingMask = UIViewAutoresizing.flexibleHeight 26 27 textView.snp.makeConstraints { (mark) in 28 mark.top.equalTo(1) 29 mark.left.equalTo(1) 30 mark.right.equalTo(1) 31 mark.bottom.equalTo(-22) 32 } 33 34 //反馈字符长度限制 35 viewBg.addSubview(label_length) 36 label_length.text = "150" 37 label_length.textColor = ColorViewBG 38 39 label_length.textAlignment = .right 40 label_length.snp.makeConstraints { (mark) in 41 mark.bottom.equalTo(-10) 42 mark.right.equalTo(-8) 43 mark.height.equalTo(12) 44 mark.width.equalTo(100) 45 } 46 47 48 }
简单的计算字符长度,在这里输入内容超过时没有做限制和提醒!
1 // MARK: -TextViewDelegate 2 3 func textViewDidChange(_ textView: UITextView) { 4 //计算剩余可输入字符长度 5 let length = textView.text.characters.count 6 label_length.text = "\(150 - length)" 7 8 9 }