textfield & Label

最多只能輸入10個字 label同步顯示字數

步驟

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

程式如下

textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool

每次textField值改變時 都會呼叫此方法

具體寫法如下

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string != "" {
if count + 1 == 11{
return false
}
count += 1
wordsCount.text = "\(count)"
}
else {
count -= 1
wordsCount.text = "\(count)"
}
return true
}

每次打一個字Label+1這大家都會

但是如果要delete就要-1

所以你不能判斷每次呼叫此方程式就+1

我發現delete時 fun給予的string是空字串 所以我就用這種方式判斷

空值-1 有值+1 total>10 return false

就醬

Like what you read? Give AnD a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.