Skip to content

Instantly share code, notes, and snippets.

@magnusws
Last active June 28, 2023 12:32
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save magnusws/3ae627e2389eb5257e51fb0e0f3b6f7a to your computer and use it in GitHub Desktop.
Save magnusws/3ae627e2389eb5257e51fb0e0f3b6f7a to your computer and use it in GitHub Desktop.
Navigation bar with a segmented control in SwiftUI
//
// SegmentedControlNavBar.swift
//
// Navigation bar with a segmented control in SwiftUI.
//
// Created by Magnus W. Solbakken on 18/05/2020.
// Copyright © 2020 Magnus W. Solbakken.
//
import SwiftUI
import UIKit
let screenSize = UIScreen.main.bounds
struct SegmentedControlNavBarDemoView: View {
let screenWidth = screenSize.width
let navBarColor = Color.white
var sections = ["first", "second", "third"]
@State private var sectionIndex = 0
init() {
let appearance = UINavigationBarAppearance()
appearance.shadowColor = .clear
appearance.backgroundEffect = .none
appearance.backgroundColor = UIColor.clear
UINavigationBar.appearance().standardAppearance = appearance
UINavigationBar.appearance().scrollEdgeAppearance = appearance
}
var body: some View {
// Navigation View
NavigationView {
ZStack {
// Content View
Group {
ZStack {
Color.accentColor.edgesIgnoringSafeArea(.all)
Text(currentSection()).foregroundColor(Color.white).bold()
}
}
// Navigation Bar
.navigationBarTitle("Navbar with picker", displayMode: .inline)
// Segmented picker
Group {
ZStack {
VStack {
Rectangle()
.fill(navBarColor)
.frame(width: screenWidth, height: 138)
Spacer()
}
.edgesIgnoringSafeArea(.all)
VStack {
ZStack {
Rectangle()
.fill(Color.clear)
.frame(width: screenWidth, height: 50)
Section {
Picker(
selection: $sectionIndex,
label: Text("Sections")
) {
ForEach(0 ..< sections.count) {
Text(self.sections[$0])
}
}.pickerStyle(SegmentedPickerStyle())
}.padding(.horizontal, 10)
}
Spacer()
}
}
}
}
}
}
// Demo content
func currentSection()-> String {
switch sectionIndex {
case 0:
return "FIRST SECTION"
case 1:
return "SECOND SECTION"
case 2:
return "THIRD SECTION"
default:
return "DEFAULT SECTION"
}
}
}
struct SegmentedControlNavBarDemoView_Previews: PreviewProvider {
static var previews: some View {
SegmentedControlNavBarDemoView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment