为UITextView添加placeholder

我们在开发中经常会遇到这样的需求:为一个UITextVIew添加placeholder。那么我们应该怎么去实现呢?下面我就来做一个带有placeholder的TextView。

1、设计思路

首先我们要明确的是这个placeholder是一个UILabel,要将它贴在UITextView上,它的内容是自适应的。在UITextView输入有文字变化的时候,placeholder是隐藏状态。

只要分析对了,代码就好实现。

2、动手实现

1、首先定义一个继承自UITextView的PlaceTextView。

class PlaceTextView: UITextView {

}

2、添加属性

    /// 属性
    fileprivate var placeholderLeftMargin: CGFloat = 5 // 默认距左5
    fileprivate var placeholderTopMargin: CGFloat = 8 // 默认距上8
    fileprivate var placeHolderFont: UIFont = UIFont.systemFont(ofSize: 16) // 默认字体大小16
    fileprivate var placeholderTextColor: UIColor = UIColor.lightGray // 默认字体颜色是lightGray
    /// 懒加载
    fileprivate lazy var placeholderLabel: UILabel = {
        let holderLb = UILabel()
        holderLb.numberOfLines = 0
        self.addSubview(holderLb)
        return holderLb
    }()
    // 反初始化
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        /// 添加监听
        NotificationCenter.default.addObserver(self, selector: #selector(textDidChange), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
    }
    
    /// 监听字数变化
    @objc private func textDidChange() {
        if self.text.count > 0 {
            placeholderLabel.isHidden = true
        } else {
            placeholderLabel.isHidden = false
        }
    }

在初始化的时候添加通知,用来监听UITextView的输入文字的变化,然后来确定placeholderLabel是否隐藏。

3、设置placeholder占位字

    /// 设置占位字
    ///
    /// - Parameter holderText: 携带占位字的回调
    func placeholder(_ holderText: (UILabel) -> Void) {
        holderText(placeholderLabel)
        placeholderLabel.font = placeHolderFont
        placeholderLabel.textColor = placeholderTextColor
        let height = placeholderLabel.text?.getHeight(self.frame.size.width - 10) ?? 0
        placeholderLabel.frame = CGRect(x: placeholderLeftMargin + 2, y: placeholderTopMargin, width: self.frame.size.width - 2 * placeholderLeftMargin, height: height)
    }
    
    /// 重写配置中的placeholderLeftMargin
    ///
    /// - Parameter leftMargin: 参数
    /// - Returns: 本身
    func placeholderLeftMargin(_ leftMargin: CGFloat) -> PlaceTextView {
        placeholderLeftMargin = leftMargin
        return self
    }
    
    /// 重新配置placeholderTopMargin
    ///
    /// - Parameter topMargin: 参数
    /// - Returns: 自身
    func placeholderTopMargin(_ topMargin: CGFloat) -> PlaceTextView {
        placeholderTopMargin = topMargin
        return self
    }
    
    /// 重新配置placeHolderFont
    ///
    /// - Parameter font: 参数
    /// - Returns: 自身
    func placeHolderFont(_ font: UIFont) -> PlaceTextView {
        placeHolderFont = font
        return self
    }
    
    /// 重新配置placeholderTextColor
    ///
    /// - Parameter color: 参数
    /// - Returns: 自身
    func placeholderTextColor(_ color: UIColor) -> PlaceTextView {
        placeholderTextColor = color
        return self
    }

下面是获取文字高度的方法:

extension String {
    /// 获取高度
    func getHeight(_ width: CGFloat,_ font: UIFont = UIFont.systemFont(ofSize: 18)) -> CGFloat {
        guard !self.isEmpty && width > 0 else {
            return 0
        }
        let text = self as NSString
        let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
        let dic = [NSAttributedStringKey.font : font]
        let rect: CGSize = text.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic, context: nil).size
        return rect.height
    }
}

好了,现在我们已经封装好一个带有placeholder的UITextView了,我们可以这样使用它:

@IBOutlet weak var textView: PlaceTextView!
...
textView.placeHolderFont(UIFont.systemFont(ofSize: 19)).placeholder { label in
    label.text = "这里是placeholder"
}

当然,你也可以在设置placeholder前设置它的各种属性,调整到适合自己的样式。

希望这篇文章能够帮助到你!

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在实际项目开发中经常有需要在UITextView中添加提示用户输入的一些文字,类似UITextField的Plac...
    海到尽头天为岸阅读 686评论 0 4
  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AGI阅读 16,009评论 3 119
  • 升级了ios 11.0之后,发现通讯录也有女朋友了
    海盗lucifer阅读 113评论 0 0
  • 我绝对不是那种靠着别人才能活的那种人 比起群体中的敷衍 孤独的常态更令我舒服 看到人的卑劣之处是我的错误
    风里栖阅读 235评论 0 0
  • https://www.cnblogs.com/wxd0108/p/5479442.html 多线程:指的是这个程...
    ZhouWG阅读 262评论 0 0