30: WordScramble, part 2

그루두·2024년 5월 14일
0

100 days of SwiftUI

목록 보기
39/108

100 days of swiftui: 30
https://www.hackingwithswift.com/100/swiftui/30

List 설정하기


TextField로 단어를 입력받고 그 단어를 List로 보여주는 View이다.

  • .onSubmit()을 이용해서 TextField에 단어를 입력하고 enter를 누르면 특정 함수를 실행하게 설정할 수 있다.
  • .textInputAutocapitalization(.never)으로 TextField에 알파벳 입력시 첫 글자의 대문자화를 막을 수 있다.
                    TextField("Enter your word", text: $newWord)
                        .textInputAutocapitalization(.never)
  • withAnimation으로 화면 내 요소가 변화할 때 애니메이션을 적용시킬 수 있다.
        withAnimation {
            usedWords.insert(word, at: 0)
        }

코드 파일
https://github.com/treesofgroo/Ios-WordScramble/blob/9439a9a7eb302334141691359c0f39ac160d4677/WordScramble/WordScramble/ContentView.swift

Bundle에서 단어 불러오기

    func startGame() {
        if let startWordsURL = Bundle.main.url(forResource: "start", withExtension: "txt") {
            if let startWordsString = try? String(contentsOf: startWordsURL) {
                let startWords = startWordsString.components(separatedBy: "\n")
                rootWord = startWords.randomElement() ?? "silkworm"
                return
            }
        }
        fatalError("Could not load start.txt from bundle.")
    }

그리고 app이 launch될 때 위 함수가 실행될 수 있도록 .onAppear(perform: startGame)를 설정했다.

단어의 유효성 검사하기

  • 입력된 단어와 기존 단어 배열의 중복성 검사하기
    func isOriginal(word: String) -> Bool {
        !usedWords.contains(word)
    }
  • 주어진 알파벳으로만 단어를 만들었는지 검사하기
    func isPossible(word: String) -> Bool {
        var tempWord = rootWord
        for letter in word {
            if let position = tempWord.firstIndex(of: letter) {
                tempWord.remove(at: position)
            } else {
                return false
            }
        }
        return true
    }
  • 실제 있는 단어인지 검사하기
    func isReal(word: String) -> Bool {
        let checker = UITextChecker()
        let range = NSRange(location: 0, length: word.utf16.count)
        let misspelledRange = checker.rangeOfMisspelledWord(in: word, range: range, startingAt: 0, wrap: false, language: "en")
        return misspelledRange.location == NSNotFound
    }
  • 각 에러에 해당하는 메시지를 만들어 alert 띄우기

코드 파일
https://github.com/treesofgroo/Ios-WordScramble/commit/b53e3ae1932f2c12fa9a4e72049742fdc84340b5

profile
계속 해보자

0개의 댓글

관련 채용 정보