100 days of swiftui: 30
https://www.hackingwithswift.com/100/swiftui/30
TextField로 단어를 입력받고 그 단어를 List로 보여주는 View이다.
.onSubmit()
을 이용해서 TextField에 단어를 입력하고 enter를 누르면 특정 함수를 실행하게 설정할 수 있다. .textInputAutocapitalization(.never)
으로 TextField에 알파벳 입력시 첫 글자의 대문자화를 막을 수 있다. TextField("Enter your word", text: $newWord)
.textInputAutocapitalization(.never)
withAnimation
으로 화면 내 요소가 변화할 때 애니메이션을 적용시킬 수 있다. withAnimation {
usedWords.insert(word, at: 0)
}
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
}
코드 파일
https://github.com/treesofgroo/Ios-WordScramble/commit/b53e3ae1932f2c12fa9a4e72049742fdc84340b5