欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > ios swift5 UITextView占位字符,记录限制字数

ios swift5 UITextView占位字符,记录限制字数

2025/11/24 12:38:26 来源:https://blog.csdn.net/baidu_40537062/article/details/142466800  浏览:    关键词:ios swift5 UITextView占位字符,记录限制字数

文章目录

  • 截图
  • 代码:具体使用
  • 代码:CustomTextView

截图

请添加图片描述

请添加图片描述

代码:具体使用

 scrollView.addSubview(contentTextView)contentTextView.placeholderLabel.text = LocalizableManager.localValue("write_comment")contentTextView.maxCharacters = 500contentTextView.backgroundColor = newUIBackColorcontentTextView.snp.makeConstraints { make inmake.left.right.equalToSuperview().inset(20)make.top.equalTo(problemLabel.snp_bottomMargin).offset(20)make.height.equalTo(150)}contentTextView.characterCountChanged = { [self] count inprint("当前输入了 \(count) 个字符")textCountLabel.text = String(count) + "/500"}

代码:CustomTextView

class CustomTextView: UITextView {// 占位文字var placeholderLabel: UILabel!// 最大字符数var maxCharacters = 200// 输入字符数变化的回调var characterCountChanged: ((Int) -> Void)?// 初始化方法override init(frame: CGRect, textContainer: NSTextContainer?) {super.init(frame: frame, textContainer: textContainer)setup()}required init?(coder: NSCoder) {super.init(coder: coder)setup()}private func setup() {// 设置代理delegate = self//设置textView的字体大小self.font = UIFont.systemFont(ofSize: 15)// 创建并设置占位文字的标签placeholderLabel = UILabel()placeholderLabel.text = LocalizableManager.localValue("report_description_tips")placeholderLabel.font = self.fontplaceholderLabel.textColor = UIColor.lightGrayplaceholderLabel.numberOfLines = 0placeholderLabel.isHidden = !self.text.isEmptyaddSubview(placeholderLabel)updatePlaceholderFrame()}override func layoutSubviews() {super.layoutSubviews()updatePlaceholderFrame()    }private func updatePlaceholderFrame() {let placeholderSize = placeholderLabel.sizeThatFits(CGSize(width: self.frame.width - 10, height: CGFloat.greatestFiniteMagnitude))placeholderLabel.frame = CGRect(x: 5, y: 5, width: placeholderSize.width, height: placeholderSize.height)}
}extension CustomTextView: UITextViewDelegate {func textViewDidChange(_ textView: UITextView) {// 更新占位文字的可见性placeholderLabel.isHidden = !textView.text.isEmpty// 限制输入的字符数if textView.text.count > maxCharacters {textView.text = String(textView.text.prefix(maxCharacters))}// 通知外部关于字符数的变化characterCountChanged?(textView.text.count)}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词