teaxtView & Label

和 textField & label差不多

最多顯示10個字 label同步顯示字數

步驟

  1. delegate拉線
  2. 繼承UITextFieldDelegate
  3. 找尋適用方法

程式碼如下

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool

每次textView更動時會呼叫

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text != "" {
if count + 1 == 11 {
return false
}
count += 1
wordsCount.text = "\(count)"
}
else {
if  count-1 == -1{
return false
}
count -= 1
wordsCount.text = "\(count)"
}
return true
}

一樣delete使用空字串判斷-1

但是唯一和textfield不同處在於0時 再按delete還會呼叫func

這樣會變成-1 textfield 0時 delete不會呼叫func

所以多寫一道判斷 等於-1時 return false

就醬

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.