100 days of swiftui: 29
https://www.hackingwithswift.com/100/swiftui/29
List는 Form과 같은 테마를 가지고 있고 요소들을 목록으로 나타낸다. 그리고 아래 사진처럼 스타일을 지정할 수 있다.
struct ContentView: View {
let cats = ["cheese", "tabby", "tuxedo", "chaos"]
var body: some View {
List{
Section("cats") {
ForEach(cats, id: \.self) {
Text($0)
}
}
Section("numbers") {
Text("1")
Text("2")
Text("3")
}
}
.listStyle(.grouped)
}
}
또는 ForEach문처럼 사용할 수도 있다.
struct ContentView: View {
let cats = ["cheese", "tabby", "tuxedo", "chaos"]
var body: some View {
List(cats, id: \.self) {
Text($0)
}
}
}
코드 파일
https://github.com/treesofgroo/Ios-WordScramble/commit/ec2864f4696461e273ae33b43be418cc3a8dbdd7
swiftui에서는 이미지를 제외한 resource는 이미지와 달리 추가 과정이 필요하다. resource와 그의 파일 형태를 필요로 한다. xcode는 ios, macos 앱을 실행할 때 자동으로 Bundle이라는 것을 만들고 여기에 파일들을 저장할 수 있도록한다.
Bundle에 파일들을 저장하면서 URL이라는 데이터 타입을 사용하는데, 웹주소뿐만 아니라 파일의 위치도 저장할 수 있다.
func testBundles() {
if let fileUrl = Bundle.main.url(forResource: "somefile", withExtension: "txt") {
if let fileContents = try? String(contentsOf: fileUrl) {
// file is loaded into a string
}
}
}
nil
일 경우를 대비하여 코드를 작성하면 된다.
코드 파일
https://github.com/treesofgroo/Ios-WordScramble/commit/a8e1a23f6f639bc1f6a054fcf915bb36f510149f
swiftui는 String을 다루는 여러 도구를 제공한다.
let input = """
a
b
c
"""
let letters = input.components(separatedBy: "\n")
let letter = letters.randomElement()
components()
는 위 input
을 특정 문자를 기준으로 분리하여 array에 담는다. 그리고 randomElement()
는 그 배열에서 무작위로 한 요소를 반환한다. 빈 문자열을 분리한다면 반환하는 값이 없을 수도 있기 때문에 nil
의 경우도 고려해야 한다.
let trimmed = letter?.trimmingCharacters(in: .whitespacesAndNewlines)
trimmingCharacters()
는 문자열의 시작과 끝의 공백(space, tab, line breaks)을 제거한다.
그리고 스펠링을 체크하는 도구인 UITextChecker
도 있다.
💡 UI로 시작하는 도구들은 UIKit에서 유래했고, Objective-C로 만들어졌다.
// 1
let word = "swift"
let checker = UITextChecker()
// 2
let range = NSRange(location: 0, length: word.utf16.count)
// 3
let misspelledRange = checker.rangeOfMisspelledWord(in: word, range: range, startingAt: 0, wrap: false, language: "en")
// 4
let allGood = misspelledRange.location == NSNotFound
print(allGood)
utf16
라는 연결다리를 이용한다.NSNotFound
로 설정된다.코드 파일
https://github.com/treesofgroo/Ios-WordScramble/commit/96174c46ed5320d45e283c393780436fe799eab9