Adding a "Hamburger" Menu to IOS application - swift

I am trying to create a hamburger menu that when you click the "hamburger" (three horizontal lines) button, the menu will slide out. I am following the tutorial found here, but the only thing that isn't working is the lines for the Hamburger image is not showing up on my application. Everything else works, but for some reason this is the one thing that is not working.
Here is my code for the ContentView, where it hosts the problem code
struct ContentView: View {
#State var showMenu = false
var body: some View {
let drag = DragGesture()
.onEnded {
if $0.translation.width < -100 {
withAnimation {
self.showMenu = false
}
}
}
return NavigationView {
GeometryReader { geometry in
ZStack(alignment: .leading) {
MainView(showMenu: self.$showMenu)
.frame(width: geometry.size.width, height: geometry.size.height)
.offset(x: self.showMenu ? geometry.size.width/2 : 0)
.disabled(self.showMenu ? true : false)
if self.showMenu {
MenuView()
.frame(width: geometry.size.width/2)
.transition(.move(edge: .leading))
}
}
.gesture(drag)
}
.navigationBarTitle("Side Menu", displayMode: .inline) // this works
//somewhere below here is the problem
.navigationBarItems(leading: (
Button(action: {
withAnimation {
self.showMenu.toggle()
}
}) {
Image(systemName: "three_horizontal_lines")
.imageScale(.large)
}
))
}
}
}
Here is the MainView:
struct MainView: View{
#Binding var showMenu: Bool
var body: some View{
Button(action: {
withAnimation{
self.showMenu = true
}
}){
Text("Show Menu")
}
}
}
Lastly, this is the MenuView:
struct MenuView: View{
var body: some View{
VStack(alignment: .leading){
HStack{
Image(systemName: "person")
.foregroundColor(.gray)
.imageScale(.large)
Text("Profile")
.foregroundColor(.gray)
.font(.headline)
}
.padding(.top, 100)
HStack{
Image(systemName: "envelope")
.foregroundColor(.gray)
.imageScale(.large)
Text("Messages")
.foregroundColor(.gray)
.font(.headline)
}
.padding(.top, 30)
HStack{
Image(systemName: "gear")
.foregroundColor(.gray)
.imageScale(.large)
Text("Settings")
.foregroundColor(.gray)
.font(.headline)
}
.padding(.top, 30)
Spacer()
}
.padding()
.frame(maxWidth: .infinity, alignment: .leading)
.background(Color(red: 32/255, green: 32/255, blue: 32/255))
.edgesIgnoringSafeArea(/*#START_MENU_TOKEN#*/.all/*#END_MENU_TOKEN#*/)
}
}
I have checked for any misspellings and even copied and pasted the code from the original tutorial, but it seems nothing allows me to see the burger image like is shown on the tutorial. Any thoughts on what else I could try?

Related

Can't display custom pop-up because my tab view is in NavigationView

I want to display a pop-up in my view, where I will be able to display a menu where I can choose how I fell, then it will show what I have chosen and close itself. If I am adding it to the view and it's presenting It shows wrong and Tab Bar does not disappear. Can someone provide a better way to show a pop-up over Tab Bar? The logic is something like this: button pressed -> shows pop-up -> choose status -> shows another pop-up -> disappears.
Code's provided below:
// Smile face that used in question
struct SmileFace: View {
var text: String
var image: String
#Binding var current: String
var body: some View {
Button {
withAnimation {
current = text
}
} label: {
VStack {
Image(image)
.resizable()
.scaledToFill()
.frame(width: 46, height: 46)
Text(text)
.foregroundColor(.white)
}
}
}
}
// Check in answer view
import SwiftUI
struct CheckInAskView: View {
let didClose: () -> Void
var didChose: Bool = false
#State var current: String
var emotions = [
"GREAT" : "good",
"GOOD" : "happy",
"OK" : "moderate",
"BAD" : "sad",
"TERRIBLE" : "verysad"
]
var body: some View {
VStack {
ZStack(alignment: .topLeading) {
Rectangle()
.fill(Color("navigation"))
.cornerRadius(15)
.frame(height: 601)
HStack(alignment: .top) {
ZStack(alignment: .top) {
Circle()
.fill(Color(red: 0.682, green: 0.384, blue: 0.486).opacity(0.10))
.frame(width: 173)
.offset(x: -173/2, y: -90/2)
.clipped()
}
Spacer()
Button {
didClose()
} label: {
ZStack {
Circle()
.fill(Color(red: 0.933, green: 0.933, blue: 0.933).opacity(0.30))
.frame(width: 24)
.clipped()
Image(systemName: "xmark")
.font(.system(size: 15))
.foregroundColor(Color(red: 0.762, green: 0.762, blue: 0.762))
}
.padding(10)
}
}
VStack(alignment: .center) {
Spacer()
Text("How do you feel now?")
.foregroundColor(.white)
.font(.custom("Manrope-Bold", size: 16))
HStack(spacing: 35) {
SmileFace(text: "GOOD", image: "good", current: $current)
}
.padding(.horizontal)
DoubleTextView(topText: "Recommendation for you", buttomText: "We have selected courses based on your goals and \nexperience", topTextSize: 16, buttomTextSize: 14)
BigFrameScrollViewHorizontal()
Spacer()
}
}
.frame(height: 601)
}
.frame(height: 601)
.transition(.move(edge: .bottom))
}
}
// View with all views
struct CheckInView: View {
#StateObject var sheetManager: SheetManager
var body: some View {
VStack {
HStack {
Text("How do you fell now?")
.foregroundColor(.white)
.font(.custom("Manrope-Bold", size: 16))
Spacer()
Button {
} label: {
ZStack {
HStack {
Text("Pass check in")
.padding([.top, .leading, .bottom])
.foregroundColor(.white)
.font(.custom("Manrope-Medium", size: 12))
Image(systemName: "chevron.right")
.foregroundColor(.white)
.font(.system(size: 15))
.padding(.trailing)
}
}
.background(Rectangle()
.fill(Color("active"))
.cornerRadius(100)
.frame(height: 26))
}
}
VStack {
Divider()
.background(Color("inactive"))
.padding(.vertical)
Divider()
.background(Color("inactive"))
.padding(.vertical)
Divider()
.background(Color("inactive"))
.padding(.vertical)
Divider()
.background(Color("inactive"))
.padding(.vertical)
Divider()
.background(Color("inactive"))
.padding(.vertical)
Divider()
.background(Color("inactive"))
.padding(.vertical)
}
HStack {
Button {
} label: {
ZStack {
Circle()
.fill(Color("navigation"))
.frame(width: 26)
Image(systemName: "chevron.left")
.foregroundColor(.white)
.font(.system(size: 14))
}
}
Button {
} label: {
ZStack {
Circle()
.fill(Color("navigation"))
.frame(width: 26)
Image(systemName: "chevron.right")
.foregroundColor(Color("inactive"))
.font(.system(size: 14))
}
}
}
.padding(.top)
}
.padding(.horizontal, 15.0)
}
}
struct CheckInView_Previews: PreviewProvider {
static var previews: some View {
CheckInView(sheetManager: SheetManager())
.background(.yellow)
}
}
If I have all of this, how can I create a pop-up over Tab View? Maybe a link to a similar problem?

SwiftUI button glitches on keyboard dismiss

I have a button on my view that, when pressed, calls a hideKeyboard function which is the following:
func hideKeyboard() {
let resign = #selector(UIResponder.resignFirstResponder)
UIApplication.shared.sendAction(resign, to: nil, from: nil, for: nil)
}
However, when the button is pressed and the keyboard gets dismissed, a glitch occurs where the button stays in place while the view moves downward:
https://giphy.com/gifs/Z7qCDpRSGoOb9CbVRQ
Reproducible example:
import SwiftUI
struct TestView: View {
#State private var username: String = ""
#State private var password: String = ""
#State private var isAnimating: Bool = false
var lightGrey = Color(red: 239.0/255.0,
green: 243.0/255.0,
blue: 244.0/255.0)
var body: some View {
ZStack() {
VStack() {
Spacer()
Text("Text")
.font(.title)
.fontWeight(.semibold)
.padding(.bottom, 15)
.frame(maxWidth: .infinity, alignment: .leading)
Text("Text")
.font(.subheadline)
.padding(.bottom)
.frame(maxWidth: .infinity, alignment: .leading)
TextField("username", text: $username)
.padding()
.background(self.lightGrey)
.cornerRadius(5.0)
.padding(.bottom, 20)
SecureField("password", text: $password)
.padding()
.background(self.lightGrey)
.cornerRadius(5.0)
.padding(.bottom, 20)
Button(action: {
self.hideKeyboard()
login()
})
{
if isAnimating {
ProgressView()
.colorScheme(.dark)
.font(.headline)
.foregroundColor(.white)
.padding()
.frame(maxWidth: .infinity)
.background(Color.green)
.cornerRadius(10.0)
.padding(.bottom, 20)
}
else {
Text("Text")
.font(.headline)
.foregroundColor(.white)
.padding()
.frame(maxWidth: .infinity)
.background(Color.green)
.cornerRadius(10.0)
.padding(.bottom, 20)
}
}
.disabled(username.isEmpty || password.isEmpty || isAnimating)
Text("Text")
.font(.footnote)
.frame(maxWidth: .infinity, alignment:.leading)
Spacer()
}
.padding()
.padding(.bottom, 150)
.background(Color.white)
}
}
func hideKeyboard() {
let resign = #selector(UIResponder.resignFirstResponder)
UIApplication.shared.sendAction(resign, to: nil, from: nil, for: nil)
}
func login() {
isAnimating = true
}
}
struct TestView_Previews: PreviewProvider {
static var previews: some View {
TestView()
}
}
This is due to view replacement inside button, find below a fixed re-layout.
Tested with Xcode 13.2 / iOS 15.2 (slow animation was activated for demo)
Button(action: {
self.hideKeyboard()
login()
})
{
VStack { // << persistent container !!
if isAnimating {
ProgressView()
.colorScheme(.dark)
}
else {
Text("Text")
}
}
.foregroundColor(.white)
.font(.headline)
.padding()
.frame(maxWidth: .infinity)
.background(Color.green)
.cornerRadius(10.0)
.padding(.bottom, 20)
}
.disabled(username.isEmpty || password.isEmpty || isAnimating)
Looks like a conflict between UIApplication.shared.sendAction and SwiftUI: hiding the keyboard starts the animation, but updating the isAnimating property resets it.
Changing the order of calls solves the problem:
Button(action: {
login()
self.hideKeyboard()
})

How to do a "reveal"-style collapse/expand animation in SwiftUI?

I'd like to implement an animation in SwiftUI that "reveals" the content of a view to enable expand/collapse functionality. The content of the view I want to collapse and expand is complex: It's not just a simple box, but it's a view hierarchy of dynamic height and content, including images and text.
I've experimented with different options, but it hasn't resulted in the desired effect. Usually what happens is that when I "expand", the whole view was shown right away with 0% opacity, then gradually faded in, with the buttons under the expanded view moving down at the same time. That's what happened when I was using a conditional if statement that actually added and removed the view. So that makes sense.
I then experimented with using a frame modifier: .frame(maxHeight: isExpanded ? .infinity : 0). But that resulted in the contents of the view being "squished" instead of revealed.
I made a paper prototype of what I want:
Any ideas on how to achieve this?
Something like this might work. You can modify the height of what you want to disclose to be 0 when hidden or nil when not so that it'll go for the height defined by the views. Make sure to clip the view afterwards so the contents are not visible outside of the frame's height when not disclosed.
struct ContentView: View {
#State private var isDisclosed = false
var body: some View {
VStack {
Button("Expand") {
withAnimation {
isDisclosed.toggle()
}
}
.buttonStyle(.plain)
VStack {
GroupBox {
Text("Hi")
}
GroupBox {
Text("More details here")
}
}
.frame(height: isDisclosed ? nil : 0, alignment: .top)
.clipped()
HStack {
Text("Cancel")
Spacer()
Text("Book")
}
}
.frame(maxWidth: .infinity)
.background(.thinMaterial)
.padding()
}
}
No, this wasn't trying to match your design, either. This was just to provide a sample way of creating the animation.
Consider the utilization of DisclosureGroup. The following code should be a good approach to your idea.
struct ContentView: View {
var body: some View {
List(0...20, id: \.self) { idx in
DisclosureGroup {
HStack {
Image(systemName: "person.circle.fill")
VStack(alignment: .leading) {
Text("ABC")
Text("Test Test")
}
}
HStack {
Image(systemName: "globe")
VStack(alignment: .leading) {
Text("ABC")
Text("X Y Z")
}
}
HStack {
Image(systemName: "water.waves")
VStack(alignment: .leading) {
Text("Bla Bla")
Text("123")
}
}
HStack{
Button("Cancel", role: .destructive) {}
Spacer()
Button("Book") {}
}
} label: {
HStack {
Spacer()
Text("Expand")
}
}
}
}
The result looks like:
I coded this in under 5 minutes. So of course the design can be optimized to your demands, but the core should be understandable.
import SwiftUI
struct TaskViewCollapsible: View {
#State private var isDisclosed = false
let header: String = "Review Page"
let url: String
let tasks: [String]
var body: some View {
VStack {
HStack {
VStack(spacing: 5) {
Text(header)
.font(.system(size: 22, weight: .semibold))
.foregroundColor(.black)
.padding(.top, 10)
.padding(.horizontal, 20)
.frame(maxWidth: .infinity, alignment: .leading)
Text(url)
.font(.system(size: 12, weight: .regular))
.foregroundColor(.black.opacity(0.4))
.padding(.horizontal, 20)
.frame(maxWidth: .infinity, alignment: .leading)
}
Spacer()
Image(systemName: self.isDisclosed ? "chevron.up" : "chevron.down")
.padding(.trailing)
.padding(.top, 10)
}
.onTapGesture {
withAnimation {
isDisclosed.toggle()
}
}
FetchTasks()
.padding(.horizontal, 20)
.padding(.bottom, 5)
.frame(height: isDisclosed ? nil : 0, alignment: .top)
.clipped()
}
.background(
RoundedRectangle(cornerRadius: 8)
.fill(.black.opacity(0.2))
)
.frame(maxWidth: .infinity)
.padding()
}
#ViewBuilder
func FetchTasks() -> some View {
ScrollView(.vertical, showsIndicators: true) {
VStack {
ForEach(0 ..< tasks.count, id: \.self) { value in
Text(tasks[value])
.font(.system(size: 16, weight: .regular))
.foregroundColor(.black)
.padding(.vertical, 0)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
}
.frame(maxHeight: CGFloat(tasks.count) * 20)
}
}
struct TaskViewCollapsible_Previews: PreviewProvider {
static var previews: some View {
TaskViewCollapsible(url: "trello.com", tasks: ["Hello", "Hello", "Hello"])
}
}

Large space above navigationTitle (Swift / SwiftUI) [duplicate]

Im currently working on a project for iOS using SwiftUI. I have 3 pages (MainMenu, CalendarList, and DateDetails.)
On the 2nd page (CalenderList) there is an empty space between the top of the screen and the actual NavigationBarTitle.
on the third page, you can see the back button (to the MainMenu) and there is two empty spaces at the top.
I've seen people use .navigationBarHidden to fix this, but i haven't been able to implement it in a way that fixes the problem.
Am i using NavigationView() incorrectly? or is there a special trick?
Here is the code for the MainMenu:
import SwiftUI
struct MainMenu: View {
var body: some View {
NavigationView {
VStack {
Text("Calendar")
.font(.largeTitle)
.fontWeight(.heavy)
.foregroundColor(Color(red: 0.055, green: 0.173, blue: 0.322))
.padding(.top, 55.0)
Text("Main Menu")
.font(.headline)
.foregroundColor(Color(red: 0.635, green: 0.635, blue: 0.635, opacity: 1.0))
/*Image("Logo")
.resizable()
.frame(width: 150.0, height: 150.0)*/
Spacer()
HStack {
NavigationLink(destination: CalendarList()) {
Image(systemName: "calendar")
.resizable()
.frame(width: 75.0, height: 75.0)
.padding()
}
NavigationLink(destination: CalendarList()) {
Image(systemName: "gear")
.resizable()
.frame(width: 75.0, height: 75.0)
.padding()
}
}
HStack {
NavigationLink(destination: StudentInfo()) {
Image(systemName: "info.circle")
.resizable()
.frame(width: 75.0, height: 75.0)
.padding()
}
NavigationLink(destination: CalendarList()) {
Image(systemName: "exclamationmark.circle")
.resizable()
.frame(width: 75.0, height: 75.0)
.padding()
}
}
Spacer()
}
}
}
}
Here is the code for CalendarList (page 2):
import SwiftUI
struct CalendarList: View {
var body: some View {
NavigationView {
List(calendarData, id: \.date) { Calendar in
if Calendar.collab {
NavigationLink(destination: DateDetails(calendar: Calendar)) {
CalendarRow(calendar: Calendar)
}
} else {
CalendarRow(calendar: Calendar)
}
}
.navigationBarTitle(Text("Schedule"))
}
}
}
And here is the code for DateDetails (page 3):
import SwiftUI
struct DateDetails: View {
var calendar: Calendar
var body: some View {
NavigationView {
VStack (alignment: .center) {
//Image("Logo")
HStack {
Text(calendar.month.prefix(4) + ".")
.font(.largeTitle)
Text(String(calendar.date).suffix(1))
.font(.largeTitle)
Spacer()
}
HStack {
Text(calendar.schedule)
.font(.title)
Spacer()
}
Spacer()
.frame(height: 30.0)
Text(calendar.info)
.font(.body)
Spacer()
}
.navigationBarTitle(String(calendar.date).prefix(4).suffix(2) + "/" + String(calendar.date).suffix(2))
.padding()
}
}
}
Only use NavigationView at the top level, you don't need to add it in every subscreen, just remove it from CalendarList and DateDetails and it will fix your spacing issue
I think you can delete the NavigationView of DateDetails.
If you want to change the navigationbar, you may want to edit navigationBarItems or change navigationBarHidden to true and customize it.
https://www.hackingwithswift.com/quick-start/swiftui/how-to-add-bar-items-to-a-navigation-view

Boundary on top of NavigationView

When I was trying to change the color of my navigation view page I realized that there is a weird boundary on top. I can't figure out what it is or how to get rid of it. Would anyone happen to know?
Here is the code.
Image with displayMode: .inline
The parent view code is the view that is presenting the page I am having trouble with.
Parent View:
Code:
import Foundation
import SwiftUI
import UIKit
struct ContentView: View {
// variable for view model
#ObservedObject var viewModel = VariableViewModel()
// SWIFT UI START
var body: some View {
// Main page
NavigationView {
ZStack {
Color(.orange).edgesIgnoringSafeArea(/*#START_MENU_TOKEN#*/.all/*#END_MENU_TOKEN#*/)
VStack {
HStack {
Spacer()
NavigationLink(destination:
SettingsView()
){
Image(systemName: "gearshape.fill").font(.system(size: 25))
}
Spacer()
Spacer()
Spacer()
Spacer()
Spacer()
Spacer()
NavigationLink(destination:
Text("You")
){
Image(systemName: "chart.bar.xaxis").font(.system(size: 25))
}
Spacer()
}
Text("Pick a mode!").font(.largeTitle).bold().offset(x: 0, y: 30)
ZStack {
VStack {
Spacer()
// ADDITION SECTION
NavigationLink(destination:
VStack {
Spacer()
MathView(operatorName: "Addition")
}
){
HStack {
Text("Addition")
Image(systemName: "plus.square")
}.font(.largeTitle)
.padding()
.background(Color.blue)
.foregroundColor(.white)
.padding(10)
.border(Color.blue, width: 5)
}
Spacer()
// SUBTRACTION SECTION
NavigationLink(destination:
VStack {
Spacer()
MathView(operatorName: "Subtraction")
}
){
HStack {
Text("Subtraction")
Image(systemName: "minus.square")
}.font(.largeTitle)
.padding()
.background(Color.blue)
.foregroundColor(.white)
.padding(10)
.border(Color.blue, width: 5)
}
Spacer()
// MULTIPLICATION SECTION
NavigationLink(destination:
VStack {
Spacer()
MathView(operatorName: "Multiplication")
}
){
HStack {
Text("Multiplication")
Image(systemName: "multiply.square")
}.font(.largeTitle)
.padding()
.background(Color.blue)
.foregroundColor(.white)
.padding(10)
.border(Color.blue, width: 5)
}
Spacer()
// DIVISION SECTION
NavigationLink(destination:
VStack {
Spacer()
MathView(operatorName: "Division")
}
){
HStack {
Text("Division")
Image(systemName: "divide.square")
}.font(.largeTitle)
.padding()
.background(Color.blue)
.foregroundColor(.white)
.padding(10)
.border(Color.blue, width: 5)
}
}
}.navigationBarHidden(true)
}
}
}.navigationViewStyle(StackNavigationViewStyle())
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Code:
import SwiftUI
struct MathView: View {
#ObservedObject var viewModel = VariableViewModel()
let operatorName: String
var body: some View {
ZStack {
Color.orange.edgesIgnoringSafeArea(.all)
VStack {
Spacer()
NavigationLink(destination:
MathContentView(operatorName: "Addition", operatorSymbol: "plus", difficultyNumber1: 5, difficultyNumber2: 5)
) {
Text("Easy")
.font(.title2)
.padding(35)
.foregroundColor(.white)
.background(Color(.systemGreen))
.cornerRadius(40)
.onAppear(perform: {
if operatorName == "Addition" {
self.viewModel.result = self.viewModel.num1 + self.viewModel.num2
} else if operatorName == "Subtraction" {
self.viewModel.result = self.viewModel.num1 - self.viewModel.num2
} else if operatorName == "Multiplication" {
self.viewModel.result = self.viewModel.num1 * self.viewModel.num2
};
withAnimation {
viewModel.resetVariables()
// numbers generator
}
})
}
Spacer()
}
}
}
}
To remove the empty space below the NavigationView add .navigationBarTitleDisplayMode(.inline) to the top view:
ZStack {
// ...
}
.navigationBarTitleDisplayMode(.inline)
Then, the slim line between the navigationViewTitle and the content below comes from the Spacer at the top of the VStack in NavigationLink that pushes the MathView.
NavigationLink(destination:
VStack {
Spacer() // this causes the *slim line*
MathView(operatorName: "Addition")
}
)
You need to remove the Spacer (and the VStack as well):
NavigationLink(destination:
MathView(operatorName: "Addition")
)