swift4 textview 字符的限制

一、预期效果图

二、页面布局

 创建一个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)
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值