Swift Catch-Up Note
かなり久々にSwiftプロジェクトをやっているので、キャッチアップが必要。メモする。
以前やったSwiftプロジェクトは7年前。Swift2の時代(ポーティングしてSwift3にした。)
最新のSwift 言語仕様
SwiftUI
新しくやるならSwiftUIかな〜。ということで、ひとまず公式チュートリアルを全部流し見するのが、一番手っ取り早いかと。
参考Links
逆引きTIPS
- Status Barを消す
// ルートのエレメントで
.statusBar(hidden: true)
- ちっこいスペーサー
Spacer()
.frame(height: 20)
- ターゲットネームで処理を変える
var plistFileName = Bundle.main.infoDictionary?["CFBundleName"]
- ターゲットごとに
#if HOGEHOGE
なdifineを置きたい
Build Setting → 表示レベルを Allにして、Other Swift Flags
を検索窓から探す。
目的のターゲットに -D HOGEHOGE
を追加する。
from stackoverflow
- JSONファイルから読み込み
import Foundation
var landmarks: [Landmark] = load("landmarkData.json")
func load<T: Decodable>(_ filename: String) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find \(filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
}
do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
}
}
- 表示されたときになんかコード実行
View()
.onAppear {
// run swift code
}
- 複数デバイスで同時にプレビュー
static var previews: some View {
ForEach(["iPhone SE (2nd generation)", "iPhone XS Max"], id: \.self) { deviceName in
LandmarkList()
.previewDevice(PreviewDevice(rawValue: deviceName))
.previewDisplayName(deviceName)
}
}
- システムデフォルトのアイコンはここにたくさんあるよ。自分でデザインしないでもsystemNameで指定すれば勝手に出るよ。
Image(systemName: "star.fill")
.foregroundColor(.yellow)
- データバインディングは
ObservableObject
@Published
@EnvironmentObject
あたりのキーワードでググりつつ、この記事を見直す。
Toggle(isOn: $showFavoritesOnly)
- SwiftUIのViewの中にUIViewControllerを置く
- SwiftUIでhome buttonを非表示にするのは大変っぽい。
Hackだけど、これが一番簡単そう。
iOS16からは
Text("Goodbye home indicator, the multitask indicator on iPad, and more.")
.persistentSystemOverlays(.hidden)
これができるぽい
- Activity Indicator てきなやつ
- SwiftUIのViewに対して、参照を持つ
- 色々ある@の違いについて…。わからん。
@State
@StateObject
@ObservedObject
@EnvironmentObject
- AppDelegateのイベントをフックしたい。
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
print("Your code here")
return true
}
}
@main
struct Testing_SwiftUI2App: App {
// inject into SwiftUI life-cycle via adaptor !!!
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
- 画像をURLからダウンロード
iOS15からはAsyncImageってのが使える。
- ダークモード対応したくない!
UIUserInterfaceStyleをinfo.plistに入れる。
- Async Await をパラレルで動かす。
- Singleton
class Singleton {
static let shared: Singleton = {
let instance = Singleton()
// setup code
return instance
}()
}
- SwiftUI作ってるときに "Extra argument in call" error
SwiftUIでは10個以上のコンポーネントを直列にならべることができないらしい。
グループ化すれば大丈夫。
- Info.plist のローカライズ
- @Stateの変更を受け取る
struct PlayerView: View {
var episode: Episode
@State private var playState: PlayState = .paused
var body: some View {
VStack {
Text(episode.title)
Text(episode.showTitle)
PlayButton(playState: $playState)
}
.onChange(of: playState) { [playState] newState in
model.playStateDidChange(from: playState, to: newState)
}
}
}
- Localization.strings はよく使う、Google Spread Sheetからの読み込みに対応できるように変換スクリプトを書いた。(Reinventing the wheel)
Xcode Cloud. 2023年12月まで無料らしいんで、試してみたけど、これはまだβ版の香りがプンプンする謎挙動が多いので、GitHub Actionsの方が正解かもな。
追記:一個一個みてくとエラー自体は解決可能。Web上に情報が少ないので辛みはあります。
アニメーションがイケてるSwiftUIサンプル集。
こういうの探してた。
iOSのシステムデフォルトの日本語フォントでHiragino Sansは、英字と並べたときの違和感をなくすため、通常のHiragino Sansより少し、小さい。という話。この人の記事はほかもかなり参考になる。
SF Symbolsの使い方。とか。
TestFlight, StoreRelease, Developmentビルドかどうかを、Swiftで
Dark Mode 対応はめんどすぎるけど、最初から、Figmaで管理されてるカラーテーマをすべてXCAssets化するのが正攻法な気がした。
SwiftUIでアニメーションする。
.matchedGeometryEffect
がシンプルで良さそう。 これをまず見る。
あと参考GitHub
Swift新しい文法async/awaitでprogressを取得する
SwiftUIで最初につまづく @
から始まるswiftの新しい文法らしいProperty Wrappers。日本語で読めるのありがたい
作っていたアプリ無事に公開したのでクローズ↓
SwiftもSwiftUIも良い言語だけど、またしばらくUnityに戻ります。