Created
January 3, 2021 07:38
-
-
Save oocoocococo/be0907482ec12d0e190db9432cad685d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct ContentView: View { | |
/// ViewModel | |
@ObservedObject var viewModel = ContentViewModel(selection: .circle, isPresented: false) | |
/// 一つ前のタブ | |
/// シートが閉じた時に選択していたタブに戻る際に利用 | |
@State var oldSelection: Tab = .circle | |
var body: some View { | |
TabView(selection: $viewModel.selection) { | |
Text("丸のビュー") | |
.tabItem { Image(systemName: "circle.fill") } | |
.tag(Tab.circle) | |
.onDisappear { | |
// 一つ前のタブを保存 | |
self.oldSelection = .circle | |
} | |
Text("三角のビュー") | |
.tabItem { Image(systemName: "triangle.fill") } | |
.tag(Tab.triangle) | |
.onDisappear { | |
// 一つ前のタブを保存 | |
self.oldSelection = .triangle | |
} | |
Text("四角のビュー") | |
.tabItem { Image(systemName: "square.fill") } | |
.tag(Tab.square) | |
} // TabView | |
.sheet(isPresented: $viewModel.isPresented) { | |
Text("シートなビュー") | |
.onDisappear { | |
// シートが閉じた時に選択していたタブに戻る | |
viewModel.dismissSheet(oldSelection: oldSelection) | |
} | |
} // sheet | |
} | |
} | |
extension ContentView { | |
enum Tab { | |
case circle | |
case triangle | |
case square | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Combine | |
final class ContentViewModel: ObservableObject { | |
/// 選択中のタブ | |
@Published var selection: ContentView.Tab | |
/// シートを表示するか | |
@Published var isPresented: Bool | |
/// Cancellables | |
private var cancellables: Set<AnyCancellable> = [] | |
init(selection: ContentView.Tab, isPresented: Bool) { | |
self.selection = selection | |
self.isPresented = isPresented | |
// タブが選択された時の処理 | |
// 丸タブ、三角タブが選択された場合はシートを表示しない | |
// 四角ビューが選択された場合はシートを表示する | |
$selection | |
.map { (selection) -> Bool in | |
switch selection { | |
case .circle, .triangle: | |
// 丸タブ、三角タブが選択された場合はシートを表示しない | |
return false | |
case .square: | |
// 四角ビューが選択された場合はシートを表示する | |
return true | |
} | |
} | |
.assign(to: \.isPresented, on: self) | |
.store(in: &cancellables) | |
} | |
/// シートが閉じた時 | |
/// - Parameter oldSelection: 選択していたタブ | |
func dismissSheet(oldSelection: ContentView.Tab) { | |
// タブを変更 | |
self.selection = oldSelection | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment