Swift:禁用带有占位符文本的UITextView中的空白/换行文本的栏按钮

时间:2016-11-21 03:28:16

标签: ios swift uitextview uitextviewdelegate

我在导航栏中有ViewControllerUITextView和“发送”栏按钮项,用于在textView中提交文本。由于UITextView不支持像UITextField这样的占位符文本,因此我自己使用以下代码处理它,该代码位于UITextViewDelegate方法shouldChangeTextInRange中。

注意:到目前为止,我编写的以下代码也为空格/换行符启用了“发送”按钮。但这是我需要帮助的:

当textView仅包含空格或换行符时如何禁用“发送”按钮,否则启用,而还适当地设置/清除占位符文本?

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {

    // Combine the postTextView text and the replacement text to
    // create the updated text string
    let currentText : NSString = textView.text
    let updatedText = currentText.stringByReplacingCharactersInRange(range, withString:text)

    // If the updated textView text will be empty, disable the send button,
    // set the placeholder text and color, and set the cursor to the beginning of the text view
    if updatedText.isEmpty {
        sendBarButton.enabled = false
        textView.text = "Write something..."
        textView.textColor = UIColor.lightGrayColor()
        textView.selectedTextRange = textView.textRangeFromPosition(textView.beginningOfDocument, toPosition: textView.beginningOfDocument)
        return false
    }

    // If the textView's placeholder is showing (i.e.: the textColor is light gray for placeholder text) 
    // and the length of the replacement string is greater than 0, 
    // clear the text view and set its color to black to prepare for the user to enter text
    else if (textView.textColor == UIColor.lightGrayColor() && !(text.isEmpty)) {
        sendBarButton.enabled = true
        textView.text = nil
        textView.textColor = UIColor.blackColor()
    }

    return true
}

更新:我了解以下代码可用于修剪/识别空格和换行符,但在这种情况下不确定如何应用它:stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).isEmpty

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

我会这样做。我在UILabel上添加了一个占位符UITextView,我将根据输入的字符数(0或非零)显示或隐藏它。

这是附加的Sample

这是 Swift 3.x 语法。它只适用于Xcode 8.x.

我刚刚使用了一些UITextView委托方法,如下面的扩展程序

所示
import UIKit

class ViewController: UIViewController {

    var placeHolderLabel:UILabel!
    @IBOutlet weak var myTextView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        placeHolderLabel = UILabel(frame: CGRect(x:5, y:5, width:240, height:22))
        placeHolderLabel.text = "Send Placeholder"

        //Set the font same as your textView font
        placeHolderLabel.font = UIFont.systemFont(ofSize: 15.0)

        //set the placeholder color
        placeHolderLabel.textColor = UIColor.lightGray

        myTextView.addSubview(placeHolderLabel)

        //Initially disable the send button
        sendButton.isEnabled = false
    }
}

// MARK: - TextView Delegates
extension ViewController:UITextViewDelegate {

    // Will handle the case for white spaces and will keep the send button disabled
    func textViewDidChange(_ textView: UITextView) {
        if(textView.text.characters.count != 0) {
            if textView.text.characters.count > 1 {
            return
            }
            textView.text = textView.text.trimmingCharacters(in: CharacterSet.whitespaces)
            if textView.text.characters.count == 0 {
                placeHolderLabel.isHidden = false
                print("Disable Button")
                sendButton.isEnabled = false
            } else {
                placeHolderLabel.isHidden = true
                print("Enable Button")
                sendButton.isEnabled = true
            }
        }
        else {
            placeHolderLabel.isHidden = false
            print("Disable Button")
            sendButton.isEnabled = false
        }
    }

    // You can modify this, as I just made my keyboard to return whenever return key is pressed.
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if(text == "\n") {
            textView.resignFirstResponder()
            return false
        }
        return true
    }

    func textViewDidBeginEditing(_ textView: UITextView) {
        if(textView.text.characters.count != 0) {
            placeHolderLabel.isHidden = true
        }
        else {
            placeHolderLabel.isHidden = false
        }
    }

    func textViewDidEndEditing(_ textView: UITextView) {
        if(textView.text.characters.count != 0) {
            placeHolderLabel.isHidden = true
        }
        else {
            placeHolderLabel.isHidden = false
        }
    }
}

答案 1 :(得分:0)

我能够使用@Rajan Maheshwari的部分答案为我自己的问题创建一个简单的解决方案(我认为它甚至可以进一步简化:

var placeholderLabel: UILabel!

func viewDidLoad() {
        placeholderLabel = UILabel(frame: CGRect(x: 5, y: 5, width: 240, height: 18))
        placeholderLabel.text = "Placeholder text..."
        placeholderLabel.textColor = UIColor.lightGrayColor()
        placeholderLabel.sizeToFit()
        postTextView.addSubview(placeholderLabel)
}

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {

        let currentText: NSString = textView.text
        let updatedText = currentText.stringByReplacingCharactersInRange(range, withString:text)
        let trimmedText = updatedText.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

        if !updatedText.isEmpty {
            // Contains any text: hide placeholder
            placeholderLabel.hidden = true
            if trimmedText.isEmpty {
                // Only whitespace and newline characters: disable button
                sendBarButton.enabled = false
            } else {
                // No whitespace- and newline-only characters: enable button
                sendBarButton.enabled = true
            }
        } else {
            // No text at all: show placeholder, disable button
            placeholderLabel.hidden = false
            sendBarButton.enabled = false
        }
        return true
    }

信用:感谢@Rajan Maheshwari的帮助!