我的应用程序使用UITextView。现在我想让UITextView有一个占位符,类似于你可以为UITextField设置的占位符。
如何做到这一点?
我的应用程序使用UITextView。现在我想让UITextView有一个占位符,类似于你可以为UITextField设置的占位符。
如何做到这一点?
当前回答
- (void)textViewDidChange:(UITextView *)textView
{
placeholderLabel.hidden = YES;
}
在textview上放一个标签。
其他回答
我已经创建了一个快速3版本的最高排名的答案
你只需要做UITextView的子类化。
import UIKit
class UIPlaceHolderTextView: UITextView {
//MARK: - Properties
@IBInspectable var placeholder: String?
@IBInspectable var placeholderColor: UIColor?
var placeholderLabel: UILabel?
//MARK: - Initializers
override func awakeFromNib() {
super.awakeFromNib()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// Use Interface Builder User Defined Runtime Attributes to set
// placeholder and placeholderColor in Interface Builder.
if self.placeholder == nil {
self.placeholder = ""
}
if self.placeholderColor == nil {
self.placeholderColor = UIColor.black
}
NotificationCenter.default.addObserver(self, selector: #selector(textChanged(_:)), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
}
func textChanged(_ notification: Notification) -> Void {
if self.placeholder?.count == 0 {
return
}
UIView.animate(withDuration: 0.25) {
if self.text.count == 0 {
self.viewWithTag(999)?.alpha = 1
}
else {
self.viewWithTag(999)?.alpha = 0
}
}
}
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
super.draw(rect)
if (self.placeholder?.count ?? 0) > 0 {
if placeholderLabel == nil {
placeholderLabel = UILabel.init()
placeholderLabel?.lineBreakMode = .byWordWrapping
placeholderLabel?.numberOfLines = 0
placeholderLabel?.font = self.font
placeholderLabel?.backgroundColor = self.backgroundColor
placeholderLabel?.textColor = self.placeholderColor
placeholderLabel?.alpha = 0
placeholderLabel?.tag = 999
self.addSubview(placeholderLabel!)
placeholderLabel?.translatesAutoresizingMaskIntoConstraints = false
placeholderLabel?.topAnchor.constraint(equalTo: self.topAnchor, constant: 7).isActive = true
placeholderLabel?.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 4).isActive = true
placeholderLabel?.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
placeholderLabel?.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
}
placeholderLabel?.text = self.placeholder
placeholderLabel?.sizeToFit()
self.sendSubview(toBack: self.placeholderLabel!)
}
if self.text.count == 0 && (self.placeholder?.count ?? 0) > 0 {
self.viewWithTag(999)?.alpha = 1
}
}
}
在swift 5。工作很好。
class BaseTextView: UITextView {
// MARK: - Views
private var placeholderLabel: UIlabel!
// MARK: - Init
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
setupUI()
startupSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupUI()
startupSetup()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
// MARK: - Setup UI
private extension BaseTextView {
func setupUI() {
addPlaceholderLabel()
textColor = .textColor
}
func addPlaceholderLabel() {
placeholderLabel = BaseLabel(frame: .zero)
placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
insertSubview(placeholderLabel, at: 0)
placeholderLabel.alpha = 0
placeholderLabel.numberOfLines = 0
placeholderLabel.backgroundColor = .clear
placeholderLabel.textColor = .lightTextColor
placeholderLabel.lineBreakMode = .byWordWrapping
placeholderLabel.isUserInteractionEnabled = false
placeholderLabel.font = UIFont.openSansSemibold.withSize(12)
placeholderLabel.topAnchor.constraint(equalTo: topAnchor, constant: 8).isActive = true
placeholderLabel.leftAnchor.constraint(equalTo: leftAnchor, constant: 5).isActive = true
placeholderLabel.rightAnchor.constraint(lessThanOrEqualTo: rightAnchor, constant: -8).isActive = true
placeholderLabel.bottomAnchor.constraint(lessThanOrEqualTo: bottomAnchor, constant: -8).isActive = true
}
}
// MARK: - Startup
private extension BaseTextView {
func startupSetup() {
addObservers()
textChanged(nil)
font = UIFont.openSansSemibold.withSize(12)
}
func addObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(textChanged(_:)), name: UITextView.textDidChangeNotification, object: nil)
}
}
// MARK: - Actions
private extension BaseTextView {
@objc func textChanged(_ sender: Notification?) {
UIView.animate(withDuration: 0.2) {
self.placeholderLabel.alpha = self.text.count == 0 ? 1 : 0
}
}
}
// MARK: - Public methods
extension BaseTextView {
public func setPlaceholder(_ placeholder: String) {
placeholderLabel.text = placeholder
}
}
更简单,并且仍然考虑到用户在某些时候输入的一些文本
BOOL placeHolderTextVisible;
在viewDidLoad上,设置它为YES(或DidMoveToSuperview,或awakeFromNib)
然后,在 - (BOOL) textView:(UITextView*)textView shouldBeginEditing
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView;
{
if (placeHolderTextVisible) {
placeHolderTextVisible = NO;
textView.text = @"";
}
return YES;
}
另一个解决方案
import UIKit
protocol PlaceholderTextViewDelegate: class {
func placeholderTextViewDidChangeText(_ text: String)
func placeholderTextViewDidEndEditing(_ text: String)
}
final class PlaceholderTextView: UITextView {
weak var notifier: PlaceholderTextViewDelegate?
var ignoreEnterAction: Bool = true
var placeholder: String? {
didSet {
text = placeholder
selectedRange = NSRange(location: 0, length: 0)
}
}
var placeholderColor = UIColor.lightGray {
didSet {
if text == placeholder {
textColor = placeholderColor
}
}
}
var normalTextColor = UIColor.lightGray
var placeholderFont = UIFont.sfProRegular(28)
fileprivate var placeholderLabel: UILabel?
// MARK: - LifeCycle
override var text: String? {
didSet {
if text == placeholder {
textColor = placeholderColor
} else {
textColor = normalTextColor
}
}
}
init() {
super.init(frame: CGRect.zero, textContainer: nil)
awakeFromNib()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
self.delegate = self
}
}
extension PlaceholderTextView: UITextViewDelegate {
// MARK: - UITextViewDelegate
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "" && textView.text == placeholder {
return false
}
if let placeholder = placeholder,
textView.text == placeholder,
range.location <= placeholder.count {
textView.text = ""
}
if ignoreEnterAction && text == "\n" {
textView.resignFirstResponder()
return false
}
return true
}
func textViewDidChange(_ textView: UITextView) {
if let placeholder = placeholder {
textView.text = textView.text.replacingOccurrences(of: placeholder, with: "")
}
if let placeholder = placeholder,
text?.isEmpty == true {
text = placeholder
textColor = placeholderColor
selectedRange = NSRange(location: 0, length: 0)
} else {
textColor = normalTextColor
}
notifier?.placeholderTextViewDidChangeText(textView.text)
}
func textViewDidChangeSelection(_ textView: UITextView) {
if let placeholder = placeholder,
text == placeholder {
selectedRange = NSRange(location: 0, length: 0)
}
}
func textViewDidEndEditing(_ textView: UITextView) {
notifier?.placeholderTextViewDidEndEditing(textView.text)
if let placeholder = placeholder,
text?.isEmpty == true {
text = placeholder
textColor = placeholderColor
selectedRange = NSRange(location: 0, length: 0)
} else {
textColor = normalTextColor
}
}
}
结果:
- (BOOL) textViewShouldBeginEditing:(UITextView *)textView
{
//NSLog(@"textViewShouldBeginEditing");
if( [tvComment.text isEqualToString:@"Comment"] && [tvComment.textColor isEqual:[UIColor lightGrayColor]] ){
tvComment.text = @"";
tvComment.textColor = [UIColor blackColor];
}
return YES;
}
- (void)keyboardWillBeHidden:(NSNotification*)aNotification{
//NSLog(@"keyboardWillBeHidden");
//Manage comment field placeholdertext
if(tvComment.text.length == 0){
tvComment.textColor = [UIColor lightGrayColor];
tvComment.text = @"Comment";
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
tvComment.textColor = [UIColor lightGrayColor];
}
TVComment是包含问题中的textView的属性。这样就可以了。