自定义UITextView(Swift)

iOS UITextView 属性


有这样一种需求,在UITextView的属性里是没有像UITextFiled一样的占位文字的,那么要让UITextView拥有占位文字,需要什么思路呢?

解决方案如下:

  • 分析:如同UITextField一样,当没有输入时显示占位文字,当有输入时随即消失,当输入完再删除时,又立刻出现
  • 由上分析,可以肯定,这个占位文字我选择一个UILable控件,因为它能够显示文字,而且便于修改占位文字属性
  • 通过分析,用通知或者代理来监听UITextView属性的改变,这里我使用通知

具体代码如下:

Swift代码

import UIKit

/// 文本视图
public class TCComposeTextView: UITextView {
    
    /// 占位标签
    fileprivate lazy var placeholderLabel = UILabel()
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        setupUI()
        setupInputAccessoryView()
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    // MARK: - 监听方法
    @objc fileprivate func textChanged() {
        placeholderLabel.isHidden = self.hasText
    }
    
    @objc fileprivate func finishInput() {
        self.resignFirstResponder()
    }
}

fileprivate extension TCComposeTextView {
    
    func setupUI() {
        NotificationCenter.default.addObserver(self, selector: #selector(textChanged), name: .UITextViewTextDidChange, object: self)
        
        placeholderLabel.text = "写下点什么吧..."
        placeholderLabel.font = self.font
        placeholderLabel.textColor = UIColor.lightGray
        placeholderLabel.frame.origin = CGPoint(x: 5, y: 8)
        placeholderLabel.sizeToFit()
        
        addSubview(placeholderLabel)
        
        delegate = self
    }
    
    func setupInputAccessoryView() {
        let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 44.0))
        let doneItem = UIBarButtonItem(title: "完成", style: .done, target: self, action: #selector(finishInput))
        let flexibleItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        toolbar.items = [flexibleItem, doneItem]
        
        self.inputAccessoryView = toolbar
    }
}

// MARK: - UITextViewDelegate
extension TCComposeTextView: UITextViewDelegate {
    public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if range.location > 99 {
            return false
        } else {
            return true
        }
    }
}

写在最后

TCComposeTextView是继承自UITextView的自定义子类,如果使用,直接创建复制粘贴即可。当然有什么问题,可以留言给我,O(∩_∩)O谢谢!

你可能感兴趣的:(自定义UITextView(Swift))