Placeholder in UITextView

前端 未结 30 3078
野趣味
野趣味 2020-11-22 16:01

My application uses an UITextView. Now I want the UITextView to have a placeholder similar to the one you can set for an UITextField.<

30条回答
  •  渐次进展
    2020-11-22 16:23

    This mimics UITextField's placeholder perfectly, where the place holder text stays until you actually type something.

    private let placeholder = "Type here"
    
    @IBOutlet weak var textView: UITextView! {
        didSet {
            textView.textColor = UIColor.lightGray
            textView.text = placeholder
            textView.selectedRange = NSRange(location: 0, length: 0)
        }
    }
    
    extension ViewController: UITextViewDelegate {
    
        func textViewDidChangeSelection(_ textView: UITextView) {
            // Move cursor to beginning on first tap
            if textView.text == placeholder {
                textView.selectedRange = NSRange(location: 0, length: 0)
            }
        }
    
        func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
            if textView.text == placeholder && !text.isEmpty {
                textView.text = nil
                textView.textColor = UIColor.black
                textView.selectedRange = NSRange(location: 0, length: 0)
            }
            return true
        }
    
        func textViewDidChange(_ textView: UITextView) {
            if textView.text.isEmpty {
                textView.textColor = UIColor.lightGray
                textView.text = placeholder
            }
        }
    }
    

提交回复
热议问题