NSDataAsset 練習 ,tableView ,資料儲存 <單字App>
Published in
7 min readAug 31, 2020
成果展示
單字發聲部分
主要英文字首英語單字app 練習儲存資料與tableView 自訂
感謝彼得給予A ~ Z 的 txt 檔 ,特別的部分
加上默背的功能可以透過switch開關來隱藏中文
加強背誦與記憶 可以再加上模擬考題練習以及錯誤紀錄…..等等
解析asset 裡的txt檔
提供的檔名為個英文字母大寫開頭
因此將使用者所點選到英文字母傳送至第二頁
再透過 let asset=NSDataAsset(name: “檔案名”)
解析出來的資料要做切割分類才能使用
let asset=NSDataAsset(name: alphalbet)if let data=asset?.data{let content=String(data: data, encoding: .utf16)//編碼格式為utf16if let lines=content?.components(separatedBy: "\n"){ //透過換行符號分行vocabularys=lines}}
解析檔案後在將檔案做分類這邊是使用空白來做分類 並show出來
func show(){let vocabulary=vocabularys[vocabularyIndex]//顯示例句用t分開vocDetail=vocabulary.components(separatedBy: "\t") //"\t"為tab跳脫字元vocabularyLabel.text=vocDetail[0] //單字self.vocabularySentences.text=vocDetail[2] //例句}
//跳脫字元複習
字串中可以使用下面這些特殊符號:
- 跳脫字元:
\0
(空字元)、\\
(反斜線)、\t
(水平 tab)、\n
(換行)、\r
(回車)、\"
(雙引號)、\'
(單引號)
儲存資料
建立收藏的資料型別並利用 Swift 中的 Codable 協議來方便編/解碼資料
定義兩個func 一個儲存一個解碼 將資料存在 Documents下
struct VocabularyCollection:Codable {
var enVoc:String var chVoc:Stringvar enSentences:Stringvar chSentences:String
static let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
//存在documentsDirectory//儲存資料static func saveToFile(vocabularyFavs: [VocabularyCollection]) {let propertyEncoder = PropertyListEncoder()if let data = try? propertyEncoder.encode(vocabularyFavs) {let url = VocabularyCollection.documentsDirectory.appendingPathComponent("vocabularyFav")try? data.write(to: url)}}static func readFromFile () -> [VocabularyCollection]? {let propertyDecoder = PropertyListDecoder()let url = VocabularyCollection.documentsDirectory.appendingPathComponent("vocabularyFav")if let data = try? Data(contentsOf: url), let vocabularyFavs = try?propertyDecoder.decode([VocabularyCollection].self, from: data) {return vocabularyFavs}else {return nil}}}
中英文單字切換動畫的部分 使用Flip Horizontal可以達到翻轉的轉場
利用座標點判斷是哪個cell的speaker被點選到
function convert(_:to:) 找出元件在tableview 上的座標找到此座標對應的 IndexPath
發出對應的英文單字聲音
@IBAction func TapSpeaker(_ sender: UIButton) {//利用轉換座標判斷點到是底幾celllet point = sender.convert(CGPoint.zero, to: tableView)if let indexPath = tableView.indexPathForRow(at: point) {let wordAudio = AVSpeechUtterance(string: vocabularyFavs[indexPath.row].enVoc)let audio = AVSpeechSynthesizer()audio.speak(wordAudio)}}
發出聲音
使用 先實例AVSpeechUtterance 在實力Audio 再透過audio.speak發出聲音
import AVFoundationlet wordAudio = AVSpeechUtterance(string: “要說的內容”)let audio = AVSpeechSynthesizer()audio.speak(wordAudio)
參考資料
完整程式碼
希望這篇文章能夠幫助到你(妳)
如有錯誤指正
I hope you found this guide helpful. If not, then please let me know either in the comments below, I’m AlberLee
Swift#19