#15 Apple Store 的 AirTag 或 AirPods Pro 刻字

rjjq
彼得潘的 Swift iOS / Flutter App 開發教室
5 min readJul 26, 2022

復刻在 AirPods 上刻字的功能

功能

  1. ScrollView 能水平切換頁面並連動 page control 元件
  2. 輸入文字會即時顯示於 AirPods 上,若超過13個字元則會跳出紅色警示,僅會於 AirPods 上最大顯示13字元
  3. 字體大小會隨著字元數增多而改變
  4. 輸入文字後於文字框跳出清空的按鍵,按下後可以清空所有設置內容
  5. 輸入完畢,點選畫面即可收下鍵盤

步驟

  1. 仿照Apple上的刻字頁面進行排版
  2. 設置 IBOutlet,scrollView是為了在設定切換頁面時,定位到新的頁面位置使用
// 錯誤訊息
@IBOutlet weak var errorMsg: UILabel!
// 刻字內容
@IBOutlet weak var letterText: UILabel!
// 分頁
@IBOutlet weak var pageControl: UIPageControl!
// 清空內容
@IBOutlet weak var clearBtn: UIButton!
// 輸入文字
@IBOutlet weak var inputText: UITextField!
@IBOutlet weak var scrollView: UIScrollView!

3. 設置IBAction,其中 changePage 則是當切換頁面時,將scrollView正確指定到各分頁的起始位置上;dismissKeyboard 則是點選畫面,能收下畫面的鍵盤

@IBAction func inputLetter(_ sender: UITextField) {
errorMsg.isHidden = true
var letter = sender.text!
// debugPrint(letter.count)
if letter.count > 0 {
clearBtn.isHidden = false
} else {
clearBtn.isHidden = true
}

if letter.count < 4 {
letterText.font = UIFont.systemFont(ofSize: 17)
} else if letter.count < 8 {
letterText.font = UIFont.systemFont(ofSize: 14)
} else {
letterText.font = UIFont.systemFont(ofSize: 11)
}

if letter.count > 13 {
errorMsg.isHidden = false
letter = String(letter.prefix(13))
}

letterText.text = letter
// debugPrint(sender.text!)
}
@IBAction func changePage(_ sender: UIPageControl) {
scrollView.setContentOffset(CGPoint(x: scrollView.bounds.width * CGFloat(sender.currentPage), y: 0), animated: true)
}
@IBAction func insertEmoji(_ sender: UIButton) {
let tag = sender.tag
inputText.text! += emoji[tag]
inputLetter(inputText)
// debugPrint(emoji[tag])
}
@IBAction func clearContent(_ sender: Any) {
inputText.text! = ""
inputLetter(inputText)
}
@IBAction func dismissKeyboard(_ sender: Any) {
view.endEditing(true)
}

4. 為了將scrollView滑動連動到 page control上,需在ViewController上指定scrollViewDidEndDecelerating的行為

extension ViewController: UIScrollViewDelegate {
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let page = scrollView.contentOffset.x / scrollView.bounds.width
pageControl.currentPage = Int(page)
}
}

成果

最困難的是各emoji 的按鍵設定及指派到對應到同一個IBAction上

GitHub

參考

--

--