給UITextView添加偽placeholder以及監(jiān)聽UITextView的Return鍵

在開發(fā)的時候我們經(jīng)常會使用到UITextField和UITextView,這兩者很像,但是UITextView沒有placeholder屬性,當(dāng)然你可以自定義一個UITextView或者給UITextView寫一個擴(kuò)展,這里我介紹一個簡單的方法做一個偽placeholder。

我這里寫了兩個UITextView并且設(shè)置了初始text


遵循UITextViewDelegate協(xié)議實現(xiàn)協(xié)議方法,在里面判斷就ok了

func textViewDidBeginEditing(textView: UITextView) {
        //開始編輯
        if textView == self.questionTitleTextView {
            if textView.text == "你的問題(5到49字以內(nèi))" {
                textView.text = ""
                textView.textColor = UIColor.blackColor()
            }
        }
        
        if textView == self.questionDetalTextView {
            if textView.text == "問題詳細(xì)描述(1000字以內(nèi))" {
                textView.text = ""
                textView.textColor = UIColor.blackColor()
            }
        }
    }
    
    func textViewDidEndEditing(textView: UITextView) {
        //結(jié)束編輯
        if textView == self.questionTitleTextView {
            if textView.text == ""{
                textView.text = "你的問題(5到49字以內(nèi))"
                textView.textColor = UIColor(red: 0.64, green: 0.64, blue: 0.64, alpha: 1)
            }
        }
        
        if textView == self.questionDetalTextView {
            if textView.text == ""{
                textView.text = "問題詳細(xì)描述(1000字以內(nèi))"
                textView.textColor = UIColor(red: 0.64, green: 0.64, blue: 0.64, alpha: 1)
            }
        }
    }

鍵盤Return鍵監(jiān)聽在UITextView的代理里面是沒有對應(yīng)方法的,這里可以用另一個方法判斷

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
        if text.containsString("\n") {
            self.view.endEditing(true)
            return false
        }
        return true
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容