作業#28 Apple Store的AirPods Pro 刻字

目的:練習即時將輸入在TextField的字顯示在Label上

功能

  1. 輸入在TextField的字即時顯示在AirPods Pro上
  2. 超過四個字時會出現UIAlertController提醒使用者
  3. 超過四個字會將TextField上第五個字移除

TextField即時顯示文字在Label上

在拉TextField的IBAction到Controller上時會有Event可以選擇如何觸發事件,這個要選擇Editing Changed在編輯時當內容有改變的時候就觸發IBAction內的程式,像下面這邊每當使用者輸入文字後,輸入框內的內容就會改變那就會觸發一次,當文字沒有超過4個字,就讓AirPods Pro上的Label顯示TextField上的文字,那如果超過了四個字就會跳出警示器,並且將TextField內的最後一個字移除,那我設定超過四個字就會執行移除,所以都會移除第五個字

@IBAction func lettering(_ sender: UITextField) {
if let inputText = sender.text{
if inputText.count > 4{
alert()
sender.text?.removeLast()
}else{
letteringLabel.text = sender.text
}
}
}

超過四字元提示使用者的UIAlertController

這邊先簡單介紹一下UIAlertController他一共有兩種顯示方式

兩種preferredStyle —.alert、.actionSheet

底下的ok按鈕是要透過UIAlertAction設定後加到UIAlertController上的,如果有很多按鈕的話是比較建議使用actionSheet,他可以堆疊成一個清單,最後有了UIAlertController本體以及UIAlertAction按鈕後,要present出來不然畫面上是看不到的

func alert(){
//本體
let alert = UIAlertController(title: "提示", message: "字元已超過四個", preferredStyle: .alert)
//按鈕
let okAction = UIAlertAction(title: "OK", style: .default) { (okAction) in
alert.dismiss(animated: true, completion: nil)
}
//將按鈕加入本體
alert.addAction(okAction)
//present出來
present(alert, animated: true, completion: nil)
}

以上內容參考下方連結:

GitHub連結:

--

--