Swift UITextView限制输入文本字符数

释放双眼,带上耳机,听听看~!

一、预期效果图

二、页面布局

创建一个label添加到bg图上,布局确定label位置

        let textView = UITextView()
textView.backgroundColor = ColorThemeShared.EEEEEE
textView.keyboardType = .emailAddress
textView.textColor = ColorThemeShared.lightTextColor
textView.font = UIFont.systemFont(ofSize: 14)
textView.delegate = self
bg.addSubview(textView)
textView.snp.makeConstraints { (make) in
make.edges.equalTo(UIEdgeInsets.init(top: 0, left: 10, bottom: 0, right: 10))
}
//
let countLabel = UILabel()
countLabel.text = "0/100字"
bg.addSubview(countLabel)
countLabel.snp.makeConstraints { (make) in
make.right.equalTo(-15)
make.bottom.equalTo(-10)
}

 三、实现UITextFieldDelegate

    func textViewDidChange(_ textView: UITextView) {
if textView.text.count > 100 {
if let str = textView.text {
//截取前100个字符
let subStr = str.prefix(100)
}
}
countLabel.text = String.init(format: "%ld/100字", textView.text.count)
}

人已赞赏
iOS文章

Swift 4.2字符串截取(subString过期)

2020-3-29 1:33:10

iOS文章

Swift 值引用与类型引用

2020-3-29 2:48:08

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索