如何在编辑时清除UITextView?

时间:2015-06-03 01:31:33

标签: swift uitextview

我目前有以下代码:

class NewPostController: UIViewController {

@IBOutlet weak var MessageField: UITextView!

override func viewDidLoad() {
    super.viewDidLoad()
    MessageField.text = "What's on your mind?"
    MessageField.textColor = UIColor.lightGrayColor()
}

func textViewDidBeginEditing(MessageField: UITextView) {
    if MessageField.textColor == UIColor.lightGrayColor() {
        MessageField.text = ""
        MessageField.textColor = UIColor.blackColor()
    }
}

但是,每当我编辑MessageField时,textViewDidBeginEditing中的代码都无法运行。我怀疑这是因为在函数中引用MessageField的方法无效,但我不知道该怎么做。

3 个答案:

答案 0 :(得分:20)

您似乎没有设置<table cellpadding="0" cellspacing="0" border="0"> <colgroup> <col /> <!-- take up rest of the space --> <col class="fixed-width" /> <!-- fixed width --> <col class="col-3" /> <!-- percentage width --> <col /> <!-- take up rest of the space --> </colgroup> <thead> <tr> <th class="align-left">Title</th> <th class="align-right">Count</th> <th class="align-left">Name</th> <th class="align-left">Single</th> </tr> </thead> <tbody> <tr> <td class="align-left">This is a very looooooooooong title that may break into multiple lines</td> <td class="align-right">19</td> <td class="align-left">Lisa McArthur</td> <td class="align-left">No</td> </tr> <tr> <td class="align-left">This is a shorter title</td> <td class="align-right">2</td> <td class="align-left">John Oliver Nielson McAllister</td> <td class="align-left">Yes</td> </tr> </tbody> </table> <table cellpadding="0" cellspacing="0" border="0"> <!-- define everything with percentage width --> <colgroup> <col class="col-6" /> <col class="col-1" /> <col class="col-4" /> <col class="col-1" /> </colgroup> <thead> <tr> <th class="align-left">Title</th> <th class="align-right">Count</th> <th class="align-left">Name</th> <th class="align-left">Single</th> </tr> </thead> <tbody> <tr> <td class="align-left">This is a very looooooooooong title that may break into multiple lines</td> <td class="align-right">19</td> <td class="align-left">Lisa McArthur</td> <td class="align-left">No</td> </tr> <tr> <td class="align-left">This is a shorter title</td> <td class="align-right">2</td> <td class="align-left">John Oliver Nielson McAllister</td> <td class="align-left">Yes</td> </tr> </tbody> </table>的{​​{1}}。

UITextView

UITextViewDelegate Protocol Reference

答案 1 :(得分:1)

让@ DanielStorm的回答在Swift 3中得以实现:

func textViewDidBeginEditing(_ textView: UITextView) {
    myTextView.text = ""
}

答案 2 :(得分:1)

除了已经给出的答案之外,我可能会采用存储的方法,它是否最初被清除为您班级的实例变量。在大多数用例中,用户只有在第一次开始编辑时才会被清除(以删除任何占位符文本):

func textViewDidBeginEditing(_ textView: UITextView) {
    if !self.textViewClearedOnInitialEdit {
        self.textView.text = ""
        self.textViewClearedOnInitialEdit = true
    }
}