I am working on a SwiftUI app, and I have a NavigationView with some buttons in the navigation bar. The problem is that after dismissing a full-page sheet (triggered by a button, not in the navigation bar), those buttons stop working.
I've tried the following, but some TestFlight users say the problem persists (I can't reproduce it myself):
Add an id to each button and change it after the dismiss (I even added it to the toolbar) to force a repaint
Add a height to buttons and navbar
Add #Environment(\.presentationMode) var presentationMode: Binding<PresentationMode> to the presenting and presented views
Set the navigation bar title display mode to inline
I saw an answer on a similar post suggesting wrapping the navigation in a UINavigation. But how do you go about that? I have wrapped views (UITextView), but do you need to wrap the controller? or the navigationItem? or just the buttons. The answer didn't elaborate.
It only seems to happen when the sheet is presented by a button outside the navigation bar. The buttons in the navigation bar also present sheets and they cause no issues. I'm tempted to just hide the navbar altogether and fake it with a regular view.
Just in case you want to see what I have, here's the relevant code in my presenting view (I removed some unrelated content and functionality):
struct PListView: View {
//https://stackoverflow.com/questions/58837007/multiple-sheetispresented-doesnt-work-in-swiftui
enum ActiveSheetProjectList: Identifiable {
case help, settings
var id: Int {
hashValue
}
}
enum ActiveFullSheetProjectList: Identifiable {
case addProject, quickCount
var id: Int {
hashValue
}
}
#ObservedObject var viewModel : ProjectListViewModel
#State var presentingDeleteProjectSheet = false
#State var itemsToDelete : [UUID]?
#State var activeSheet: ActiveSheetProjectList?
#State var activeFullSheet : ActiveFullSheetProjectList?
#ObservedObject var settings : Settings
#Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
init(settings: Settings) {
self.viewModel = ProjectListViewModel()
self.settings = settings
//https://medium.com/#francisco.gindre/customizing-swiftui-navigation-bar-8369d42b8805
// this is not the same as manipulating the proxy directly
let appearance = UINavigationBarAppearance()
// this overrides everything you have set up earlier.
appearance.configureWithTransparentBackground()
appearance.backgroundColor = UIColor(Color.navBar)
// this only applies to big titles
appearance.largeTitleTextAttributes = [
.font : UIFont.systemFont(ofSize: 20),
NSAttributedString.Key.foregroundColor : UIColor(Color.smallTextMain)
]
// this only applies to small titles
appearance.titleTextAttributes = [
.font : UIFont.systemFont(ofSize: 20),
NSAttributedString.Key.foregroundColor : UIColor(Color.smallTextMain)
]
//In the following two lines you make sure that you apply the style for good
UINavigationBar.appearance().scrollEdgeAppearance = appearance
UINavigationBar.appearance().standardAppearance = appearance
// This property is not present on the UINavigationBarAppearance
// object for some reason and you have to leave it til the end
UINavigationBar.appearance().tintColor = UIColor(Color.smallTextMain)
}
var body: some View {
NavigationView {
ZStack {
Color.background.edgesIgnoringSafeArea(.all)
VStack {
List {
ForEach(projects) { project in
NavigationLink(destination: ProjectView(project: project, settings: settings, viewModel: ProjectListViewModel(), viewContext: viewContext)
.environmentObject(self.settings)
{
HStack {
Text(project.name ?? "").font(.headline).padding(.bottom, 5).padding(.top, 5)
}
}
.listRowInsets(.init(top: 10, leading: 3, bottom: 10, trailing: 3))
.accessibilityHint(Text(NSLocalizedString("View project details", comment: "")))
}
.onDelete(perform: { indexSet in
presentingDeleteProjectSheet = true
itemsToDelete = indexSet.map { projects[$0].id! }
})
.listRowBackground(Color.lightGray)
.padding(0)
.actionSheet(isPresented: $presentingDeleteProjectSheet) {
var name = NSLocalizedString("Project", comment: "Generic label")
if let id = itemsToDelete?.first {
name = projects.first(where: {$0.id == id})?.name ?? ""
}
return ActionSheet(title: Text(NSLocalizedString(String.localizedStringWithFormat("Delete %#", name), comment: "alert title")), message: Text(NSLocalizedString("Deleting a project can't be undone", comment: "Deleting alert message")), buttons: [
.destructive(Text(NSLocalizedString("Delete", comment: "Button label"))) {
if itemsToDelete != nil {
viewModel.deleteProjects(projects: activeProjectsDateCreated, ids: itemsToDelete!)
}
},
.cancel({itemsToDelete?.removeAll()})
])
}
}
.padding(0)
.onAppear(perform: {
UITableView.appearance().backgroundColor = UIColor(Color.lightGray)
UITableViewCell.appearance().selectionStyle = .none
})
}
}
}
.fullScreenCover(item: $activeFullSheet, content: { item in
switch item {
case .quickCount :
// THIS IS THE SHEET THAT CAUSES THE ISSUES
QuickCountView(viewModel: CounterViewModel(counter: viewModel.getScratchCounter(projects: quickCountProject), sound: settings.sound, showTotal: settings.showTotal, viewContext: viewContext))
.environmentObject(settings)
case .addProject:
// No problems after dismissing this one
AddEditProjectView(viewModel: AddEditProjectViewModel(project : nil, startAt: settings.startNumber, viewContext: viewContext), isNew: true, isEditing: .constant(true))
.environmentObject(settings)
}
})
Button(action: { activeFullSheet = .quickCount }, label: {
Text(NSLocalizedString("Quick Count +", comment: "Button label"))
.accessibilityLabel(NSLocalizedString("Quick count", comment: ""))
})
.buttonStyle(CustomButton(style: .button, size: .large))
.padding()
.sheet(item: $activeSheet) { item in
switch item {
case .help:
HelpView()
case .settings:
SettingsView()
.environmentObject(settings)
}
}
}
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItemGroup(placement: .navigationBarLeading) {
HStack {
Button(action: {
self.activeSheet = .settings
}) {
Image(systemName: "gearshape.fill")
.font(Font.system(size: 28, weight: .medium, design: .rounded))
.foregroundColor(Color.main)
.accessibilityLabel(Text(NSLocalizedString("Settings", comment: "a11y label")))
.frame(height: 96, alignment: .trailing)
}
Button(action: {
self.activeSheet = .help
}) {
Image(systemName: "questionmark")
.font(Font.system(size: 28, weight: .semibold, design: .rounded))
.foregroundColor(Color.main)
.accessibilityLabel(Text(NSLocalizedString("Help", comment: "a11y label")))
.frame(height: 96, alignment: .trailing)
}
}
}
ToolbarItemGroup(placement: .navigationBarTrailing) {
HStack {
Button(action: { activeFullSheet = .addProject }) {
Image(systemName: "plus")
.font(Font.system(size: 30, weight: .semibold))
.foregroundColor(Color.main)
.accessibilityLabel(Text(NSLocalizedString("Add a Project", comment: "a11y label")))
.frame(height: 96, alignment: .trailing)
}
Button(action: {
self.isEditing.toggle()
}) {
Image(systemName: isEditing ? "xmark" : "pencil")
.font(Font.system(size: 28, weight: .black))
.foregroundColor(activeProjectsDateCreated.count >= 1 ? Color.main : Color.gray)
.accessibilityLabel(Text(NSLocalizedString("Edit Project List", comment: "a11y label")))
.frame(height: 96, alignment: .trailing)
}.disabled(activeProjectsDateCreated.count < 1)
.frame(height: 96, alignment: .trailing)
}
}
}
}
}
Related
I have created a custom element I am calling Slide. I have a LazyVGrid that is displaying my Slide elements. My issue is that when I update the data array that my grid is using, the Slide elements are not updating.
Scenario:
User clicks on the options button on a Slide and changes the Slide color, I am then updating the data array but the Slide element doesn't update despite the data being correct (I have verified this by adding Text(slide.color) into the LazyVGrid which displays the newly set color as expected)
My Suspicions:
I am assuming it doesn't update because I have something wrong in the Slide struct, I am quite new to SwiftUI so I am learning as I go. I must also mention that this loads and displays correctly when I first display the view, the only issue is that it doesn't update when I update the SlideStructure.
Here is the Code:
struct ShowSongFile : View {
#EnvironmentObject var SlideStructure : SlidesModel
#State var selectedSlide : SplaySlide? = nil
var columns = [GridItem(.adaptive(minimum: 320))]
var body: some View {
ScrollView {
LazyVGrid(columns: columns, alignment: .trailing, spacing: 20) {
ForEach(SlideStructure.SongSlides, id:\.id) { slide in
if slide.id == selectedSlide?.id {
Slide(IsSelected:true, SlideData: slide)
} else {
Slide(IsSelected:false, SlideData: slide)
.onTapGesture {
selectSlide(Slide: slide)
}
}
}
}.onAppear(perform: loadSelectedFile)
}
}
Here is the Slide File which also shows how I am setting the colours for the slides:
struct Slide : View {
#State var EnableSlideEditing : Bool? = false
#State var IsSelected : Bool = false
#State var SlideData : SplaySlide
#EnvironmentObject var SlideStructure : SlidesModel
var body : some View {
VStack {
Group{
VStack(alignment: .center) {
let editor = TextEditor(text: $SlideData.lyric)
.multilineTextAlignment(.center)
.padding()
let text = Text(SlideData.lyric)
.multilineTextAlignment(.center)
.frame(width: 320.0, height: 160.0)
if EnableSlideEditing ?? false {
editor
} else {
text
}
Group {
HStack {
Text(SlideData.slideType)
.padding(.leading, 5.0)
Spacer()
MenuButton(label: Image(systemName: "ellipsis.circle")) {
Button("Edit Slide Text", action: {EnableSlideEditing?.toggle()})
Divider()
Menu("Slide Type") {
Button("Verse", action: {SlideType(Type: "Verse", ColorHex: "#f57242")})
Button("Chorus", action: {SlideType(Type: "Chorus", ColorHex: "#0068bd")})
Button("Pre-Chorus", action: {SlideType(Type: "Pre-Chorus", ColorHex: "#02ad96")})
Button("Tag", action: {SlideType(Type: "Tag", ColorHex: "#ad027d")})
Button("Bridge", action: {SlideType(Type: "Bridge", ColorHex: "#02ad96")})
}
Menu("Transitions") {
Button("Option 1", action: {})
Button("Option 2", action: {})
}
Divider()
Button("Delete Slide", action: {})
Button("Duplicate Slide", action: {})
}
.menuButtonStyle(BorderlessButtonMenuButtonStyle())
.frame(alignment: .trailing)
.padding(.trailing, 5.0)
.buttonStyle(PlainButtonStyle())
}
}
.frame(width: 320, height: 20, alignment: .leading)
.background(Color.init(hex: SlideData.slideBorderColorHex))
}
}
.frame(width: 320, height: 180, alignment: .bottomLeading)
.background(IsSelected ? Color.accentColor : .black)
.cornerRadius(10)
}
}
func SlideType(Type:String, ColorHex: String) {
for (index, slide) in SlideStructure.SongSlides.enumerated() {
if slide.id == self.SlideData.id {
SlideStructure.SongSlides[index].slideBorderColorHex = ColorHex
SlideStructure.SongSlides[index].slideType = Type
ShowSongFile.main?.SongFile.slides = SlideStructure.SongSlides
ShowSongFile.main!.SongFile.SaveSongToDisk()
}
}
}
}
SlideStructure: (SlideModel)
class SlidesModel : ObservableObject {
#Published var SongSlides : [SplaySlide] = []
}
There are too many missing parts to be able to test any particular solution, so I will take a guess.
In ShowSongFile you could try :
LazyVGrid(columns: columns, alignment: .trailing, spacing: 20) {
ForEach(SlideStructure.SongSlides, id:\.id) { slide in
Slide(SlideData: slide) // <--- here
.onTapGesture {
selectSlide(Slide: slide)
}
.background(slide.id == selectedSlide?.id ? Color.accentColor : .black) // <--- here
}
and adjust Slide accordingly, that is, remove IsSelected and .background(IsSelected ? Color.accentColor : .black).
P.S: your naming and case of your variables and functions makes
reading your code less than appealing.
so I am trying to have a view update to display a custom view based on a user selection from another view. This is a simple task app project I started to get a better understanding of SwiftUI and have hit my first major roadblock. The custom view is generated from a Tag object from Core Data, so it would be this information that is passed from View 2 to View 1.
I've marked where the update would take place as well as where the action is performed with TODOs. Hopefully I did a good job at explaining what I am hoping to accomplish, nothing I have tried seems to work. I am sure it's something simple but the solution is evading me.
View 1: View that needs to be updated when user returns
View 2: View where selection is made
The View that needs to be updated and its ViewModel.
struct AddTaskView: View {
//MARK: Variables
#Environment(\.managedObjectContext) var coreDataHandler
#Environment(\.presentationMode) var presentationMode
#StateObject var viewModel = AddTaskViewModel()
#StateObject var taskListViewModel = TaskListViewModel()
#State private var title: String = ""
#State private var info: String = ""
#State private var dueDate = Date()
var screenWidth = UIScreen.main.bounds.size.width
var screenHeight = UIScreen.main.bounds.size.height
var body: some View {
VStack(spacing: 20) {
Text("Add a New Task")
.font(.title)
.fontWeight(.bold)
//MARK: Task.title Field
TextField("Task", text: $title)
.font(.headline)
.padding(.leading)
.frame(height: 55)
//TODO: Update to a specific color
.background(Color(red: 0.9, green: 0.9, blue: 0.9))
.cornerRadius(10)
//MARK: Task.tag Field
HStack {
Text("Tag")
Spacer()
//TODO: UPDATE TO DISPLAY TAG IF SELECTED OTHERWISE DISPLAY ADDTAGBUTTONVIEW
NavigationLink(
destination: TagListView(),
label: {
AddTagButtonView()
}
)
.accentColor(.black)
}
//MARK: Task.info Field
TextEditor(text: $info)
.frame(width: screenWidth - 40, height: screenHeight/4, alignment: .center)
.autocapitalization(.sentences)
.multilineTextAlignment(.leading)
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.black, lineWidth: 0.5)
)
//MARK: Task.dateDue Field
DatePicker(
"Due Date",
selection: $dueDate,
in: Date()...
)
.accentColor(.black)
.font(.headline)
Spacer()
Button(action: {
viewModel.addTask(taskTitle: title, taskInfo: info, taskDueDate: dueDate)
//Dismiss View if successful
self.presentationMode.wrappedValue.dismiss()
}, label: {
Text("Add Task")
.frame(width: 150, height: 60)
.font(.headline)
.foregroundColor(.black)
.background(Color.yellow)
.cornerRadius(30)
})
}
.padding()
.navigationBarTitleDisplayMode(.inline)
}
}
final class AddTaskViewModel : ObservableObject {
var coreDataHandler = CoreDataHandler.shared
#Published var tag : Tag?
func addTask(taskTitle: String, taskInfo: String, taskDueDate: Date) {
let newTask = Task(context: coreDataHandler.container.viewContext)
newTask.title = taskTitle
newTask.info = taskInfo
newTask.dateCreated = Date()
newTask.dateDue = taskDueDate
newTask.completed = false
newTask.archived = false
coreDataHandler.save()
}
}
The View where the selection is made and its ViewModel
struct TagListView: View {
#FetchRequest(entity: Tag.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Tag.title, ascending: true)]) var tagList : FetchedResults<Tag>
#Environment(\.presentationMode) var presentationMode
#StateObject var viewModel = TagListViewModel()
var body: some View {
VStack {
HStack {
Text("Create a Tag")
.font(.system(size: 20))
.fontWeight(.medium)
Spacer()
NavigationLink(
destination: CreateTagView(),
label: {
Image(systemName: "plus.circle")
.font(.system(size: 25))
})
}
Divider()
.padding(.bottom, 10)
ScrollView(.vertical, showsIndicators: false, content: {
if tagList.count != 0 {
LazyVStack(spacing: 20) {
ForEach(tagList, id: \.self) { tag in
let tagColour = Color(red: tag.colourR, green: tag.colourG, blue: tag.colourB, opacity: tag.colourA)
Button {
//TODO: UPDATE ADDTASKVIEW TO DISPLAY THE SELECTED TAG
//Dismiss view
self.presentationMode.wrappedValue.dismiss()
} label: {
TagView(title: tag.title ?? "Tag", color: tagColour, darkText: false)
}
}
}
} else {
Text("Add your first tag.")
}
})
}
.padding()
}
}
final class TagListViewModel : ObservableObject {
}
Problem:
I am unable to force my alpha, beta, or gamma buttons to turn ON when an input parameter is passed from Landing.swift.
I do not understand why when onAppear fires in the stack, the output becomes:
gamma is the title
beta is the title
alpha is the title
gamma is the title
beta is the title
alpha is the title
Confused -> Why is this outputting 2x when the ForEach loop has only 3 elements inside?
Background:
I am trying to pass a parameter from one view (Landing.swift) to another (ContentView.swift) and then based on that parameter force the correct button (in ContentView) to trigger an ON state so it's selected. I have logic shown below in ButtonOnOff.swift that keeps track of what's selected and not.
For instance, there are 3 buttons in ContentView (alpha, beta, and gamma) and based on the selected input button choice from Landing, the respective alpha, beta, or gamma button (in ContentView) should turn ON.
I am dynamically generating these 3 buttons in ContentView and want the flexibility to extend to possibly 10 or more in the future. Hence why I'm using the ForEach in ContentView. I need some help please understanding if I'm incorrectly using EnvironmentObject/ObservedObject or something else.
Maintaining the ON/OFF logic works correctly with the code. That is, if you manually press alpha, it'll turn ON but the other two will turn OFF and so forth.
Thanks for your help in advance! :)
Testing.swift
import SwiftUI
#main
struct Testing: App {
#StateObject var buttonsEnvironmentObject = ButtonOnOff()
var body: some Scene {
WindowGroup {
Landing().environmentObject(buttonsEnvironmentObject)
}
}
}
Landing.swift
import SwiftUI
struct Landing: View {
#State private var tag:String? = nil
var body: some View {
NavigationView {
ZStack{
HStack{
NavigationLink(destination: ContentView(landingChoice:tag ?? ""), tag: tag ?? "", selection: $tag) {
EmptyView()
}
Button(action: {
self.tag = "alpha"
}) {
HStack {
Text("alpha")
}
}
Button(action: {
self.tag = "beta"
}) {
HStack {
Text("beta")
}
}
Button(action: {
self.tag = "gamma"
}) {
HStack {
Text("gamma")
}
}
}
.navigationBarHidden(true)
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
}
ContentView.swift
import SwiftUI
struct ContentView: View {
var btnName:String
#EnvironmentObject var buttonEnvObj:ButtonOnOff
init(landingChoice:String){
self.btnName = landingChoice
print("\(self.btnName) is the input string")
}
var body: some View {
VStack{
Form{
Section{
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing:10) {
ForEach(0..<buttonEnvObj.buttonNames.count) { index in
BubbleButton(label: "\(buttonEnvObj.buttonNames[index])")
.padding(EdgeInsets(top: 5, leading: 5, bottom: 5, trailing: 0))
.onAppear {
print("\(buttonEnvObj.buttonNames[index]) is the title")
}
}
}
}.frame(height: 50)
}
}
}
}
}
struct BubbleButton: View{
#EnvironmentObject var buttonBrandButtons:ButtonOnOff
var label: String
var body: some View{
HStack{
Button(action: {
print("Button action")
buttonBrandButtons.changeState(buttonName: self.label)
}) {
ZStack {
VStack{
HStack {
Spacer()
Text(label)
.font(.system(size: 12,weight:.regular, design: .default))
.foregroundColor(buttonBrandButtons.buttonBrand[self.label]! ? Color.white : Color.gray)
Spacer()
}
}
.frame(height:30)
.fixedSize()
}
}
.background(buttonBrandButtons.buttonBrand[self.label]! ? Color.blue : .clear)
.cornerRadius(15)
.overlay(buttonBrandButtons.buttonBrand[self.label]! ?
RoundedRectangle(cornerRadius: 15).stroke(Color.blue,lineWidth:1) : RoundedRectangle(cornerRadius: 15).stroke(Color.gray,lineWidth:1))
.animation(.linear, value: 0.15)
}
}
}
ButtonOnOff.swift
import Foundation
class ButtonOnOff:ObservableObject{
var buttonNames = ["alpha","beta","gamma"]
#Published var buttonBrand:[String:Bool] = [
"alpha":false,
"beta":false,
"gamma":false
]
func changeState(buttonName:String) -> Void {
for (key,_) in buttonBrand{
if key == buttonName && buttonBrand[buttonName] == true{
buttonBrand[buttonName] = false
} else{
buttonBrand[key] = (key == buttonName) ? true : false
}
}
print(buttonBrand)
}
}
For a short answer just add
.onAppear(){
buttonEnvObj.changeState(buttonName: self.btnName)
}
to ContentView that will highlight the button that was selected.
As for a solution that can be expanded at will. I would suggest a single source of truth for everything and a little simplifying.
struct Landing: View {
#EnvironmentObject var buttonEnvObj:ButtonOnOff
#State private var tag:String? = nil
var body: some View {
NavigationView {
ZStack{
HStack{
NavigationLink(destination: ContentView(), tag: tag ?? "", selection: $tag) {
EmptyView()
}
//Put your buttons here
HStack{
//Use the keys of the dictionary to create the buttons
ForEach(buttonEnvObj.buttonBrand.keys.sorted(by: <), id: \.self){ key in
//Have the button set the value when pressed
Button(action: {
self.tag = key
buttonEnvObj.changeState(buttonName: key)
}) {
Text(key)
}
}
}
}
.navigationBarHidden(true)
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
}
struct ContentView: View {
#EnvironmentObject var buttonEnvObj:ButtonOnOff
var body: some View {
VStack{
Form{
Section{
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing:10) {
//Change this to use the dictionary
ForEach(buttonEnvObj.buttonBrand.sorted(by: {$0.key < $1.key }), id:\.key) { key, value in
BubbleButton(key: key, value: value)
.padding(EdgeInsets(top: 5, leading: 5, bottom: 5, trailing: 0))
.onAppear {
print("\(value) is the title")
}
}
}
}.frame(height: 50)
}
}
}
}
}
struct BubbleButton: View{
#EnvironmentObject var buttonBrandButtons:ButtonOnOff
var key: String
var value: Bool
var body: some View{
HStack{
Button(action: {
print("Button action")
buttonBrandButtons.changeState(buttonName: key)
}) {
ZStack {
VStack{
HStack {
Spacer()
Text(key)
.font(.system(size: 12,weight:.regular, design: .default))
.foregroundColor(value ? Color.white : Color.gray)
Spacer()
}
}
.frame(height:30)
.fixedSize()
}
}
.background(value ? Color.blue : .clear)
.cornerRadius(15)
.overlay(value ?
RoundedRectangle(cornerRadius: 15).stroke(Color.blue,lineWidth:1) : RoundedRectangle(cornerRadius: 15).stroke(Color.gray,lineWidth:1))
.animation(.linear, value: 0.15)
}
}
}
class ButtonOnOff:ObservableObject{
//Get rid of this so you can keep the single source
//var buttonNames = ["alpha","beta","gamma"]
//When you want to add buttons just add them here it will all adjust
#Published var buttonBrand:[String:Bool] = [
"alpha":false,
"beta":false,
"gamma":false
]
func changeState(buttonName:String) -> Void {
for (key,_) in buttonBrand{
if key == buttonName && buttonBrand[buttonName] == true{
buttonBrand[buttonName] = false
} else{
buttonBrand[key] = (key == buttonName) ? true : false
}
}
print(buttonBrand)
}
}
My Custom button does not tap and passes to next view called AddCreditCardView.
I have tested the button action with print statement and it won't work too.
I copied my code below in separate.
This is my ContentView
import SwiftUI
struct ContentView: View {
let membershipRows = MembershipData.listData()
let corporateRows = CorporateData.listData()
let otherOperationRows = OtherOperationsData.listData()
#State var selectedCard = CreditCard(id: "", cardOwnerName: "", cardNumber: "", cardExpMonth: "", cardExpYear: "", ccv: "")
#State var shown: Bool = false
var body: some View {
NavigationView {
VStack {
List {
Section(header: Text("Bireysel")) {
ForEach(membershipRows) { row in
NavigationLink(destination: CreditCardView()) {
RowElementView(row: row)
}
}
}
if self.corporateRows.count == 0
{
Rectangle()
.background(Color(.white))
.edgesIgnoringSafeArea(.all)
.foregroundColor(.white)
.padding(.vertical,32)
}
else {
Section(header: Text("Kurumsal")) {
ForEach(corporateRows) { row in
RowElementView(row: row)
}
}
}
Section(header: Text("Diger Islemler")) {
ForEach(otherOperationRows) { row in
RowElementView(row: row)
}
}
Rectangle()
.foregroundColor(.clear)
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height )
}
.navigationBarTitle("Odeme Yontemleri", displayMode: .inline)
.font(Font.custom("SFCompactDisplay", size: 16))
Button(action: {
AddCreditCardView(item: self.selectedCard)
}, label: { CustomButton(title: "Odeme Yontemi Ekle", icon: .none, status: .enable)
})
}
}
}
This is my AddCreditCardView
import SwiftUI
struct AddCreditCardView: View {
var item: CreditCard
var body: some View {
NavigationView {
VStack {
TopBar()
Spacer()
CardInfo()
Spacer()
}
.navigationBarTitle("Odeme Yontemi", displayMode: .inline)
}
}
}
struct TopBar : View {
var body: some View {
VStack {
HStack() {
Image("addcreditcard")
Image("line")
Image("locationBar")
Image("line")
Image("check-circle")
}
.padding(.horizontal,62)
VStack {
Text("Kredi Karti Ekle")
.font(Font.custom("SFCompactDisplay-Bold", size: 14))
Text("1. Adim")
.font(Font.custom("SFCompactDisplay", size: 14))
.fontWeight(.regular)
.foregroundColor(.gray)
}
}
.padding()
}
}
struct CardInfo : View {
var body: some View {
VStack {
CustomTextField(tFtext: "Kartin Uzerindeki Isim", tFImage: "user")
.textContentType(.givenName)
CustomTextField(tFtext: "Kredi Kart Numarasi", tFImage: "credit")
.textContentType(.oneTimeCode)
.keyboardType(.numberPad)
HStack {
CreditCardDateTextField(tFtext: "", tFImage: "date")
.textContentType(.creditCardNumber)
Spacer()
Text("|")
.foregroundColor(.black)
.overlay(
Rectangle()
.frame(width: 60, height: 53))
CustomTextField(tFtext: "CCV", tFImage: "")
.textContentType(.creditCardNumber)
}
.foregroundColor(Color(#colorLiteral(red: 0.9647058824, green: 0.9725490196, blue: 0.9882352941, alpha: 1)))
CustomTextField(tFtext: "Kart Ismi", tFImage: "cardEdit")
Spacer()
}
}
}
And Finally, this is my CreditCard Model
import SwiftUI
struct CreditCard: Identifiable {
var id: String = UUID().uuidString
var cardOwnerName : String
var cardNumber: String
var cardExpMonth: String
var cardExpYear: String
var ccv: String
Seems like you are trying to navigate to AddCreditCardView on the button press. The action closure can not present a view automatically like that! You should change that code to something like this:
#State var navigated = false
,,,
NavigationLink("AddCreditCardView", destination: AddCreditCardView(), isActive: $navigated)
Button(action: { self.navigated.toggle() },
label: { CustomButton(title: "Odeme Yontemi Ekle", icon: .none, status: .enable) })
changing the navigated state will show the next page as it seems you wished.
I have a Plus button in my first view. Looks like a FAB button. I want to hide it after I tap some step wrapped in NavigationLink. So far I have something like this:
ForEach(0 ..< 12) {item in
NavigationLink(destination: TransactionsDetailsView()) {
VStack {
HStack(alignment: .top) {
Text("List item")
}
.padding(EdgeInsets(top: 5, leading: 10, bottom: 5, trailing: 10))
.foregroundColor(.black)
Divider()
}
}
.simultaneousGesture(TapGesture().onEnded{
self.showPlusButton = false
})
.onAppear(){
self.showPlusButton = true
}
}
It works fine with single tap. But when I long press NavigationLink it doesn't work. How should I rewrite my code to include long press as well? Or maybe I should make it work different than using simultaneousGesture?
I'm using the following code. I prefer it to just NavigationLink by itself because it lets me reuse my existing ButtonStyles.
struct NavigationButton<Destination: View, Label: View>: View {
var action: () -> Void = { }
var destination: () -> Destination
var label: () -> Label
#State private var isActive: Bool = false
var body: some View {
Button(action: {
self.action()
self.isActive.toggle()
}) {
self.label()
.background(
ScrollView { // Fixes a bug where the navigation bar may become hidden on the pushed view
NavigationLink(destination: LazyDestination { self.destination() },
isActive: self.$isActive) { EmptyView() }
}
)
}
}
}
// This view lets us avoid instantiating our Destination before it has been pushed.
struct LazyDestination<Destination: View>: View {
var destination: () -> Destination
var body: some View {
self.destination()
}
}
And to use it:
var body: some View {
NavigationButton(
action: { print("tapped!") },
destination: { Text("Pushed View") },
label: { Text("Tap me") }
)
}
Yes, NavigationLink does not allow such simultaneous gestures (might be as designed, might be due to issue, whatever).
The behavior that you expect might be implemented as follows (of course if you need some chevron in the list item, you will need to add it manually)
struct TestSimultaneousGesture: View {
#State var showPlusButton = false
#State var currentTag: Int?
var body: some View {
NavigationView {
List {
ForEach(0 ..< 12) { item in
VStack {
HStack(alignment: .top) {
Text("List item")
NavigationLink(destination: Text("Details"), tag: item, selection: self.$currentTag) {
EmptyView()
}
}
.padding(EdgeInsets(top: 5, leading: 10, bottom: 5, trailing: 10))
.foregroundColor(.black)
Divider()
}
.simultaneousGesture(TapGesture().onEnded{
print("Got Tap")
self.currentTag = item
self.showPlusButton = false
})
.simultaneousGesture(LongPressGesture().onEnded{_ in
print("Got Long Press")
self.currentTag = item
self.showPlusButton = false
})
.onAppear(){
self.showPlusButton = true
}
}
}
}
}
}
Another alternative I have tried. Not using simultaneousGesture, but an onDisappear modifier instead. Code is simple and It works. One downside is that those actions happen with a slight delay. Because first the destination view slides in and after this the actions are performed. This is why I still prefer #Asperi's answer where he added .simultaneousGesture(LongPressGesture) to my code.
ForEach(0 ..< 12) {item in
NavigationLink(destination: TransactionsDetailsView()) {
VStack {
HStack(alignment: .top) {
Text("List item")
}
.padding(EdgeInsets(top: 5, leading: 10, bottom: 5, trailing: 10))
.foregroundColor(.black)
Divider()
}
}
.onDisappear(){
self.showPlusButton = false
}
.onAppear(){
self.showPlusButton = true
}
}
I have tried an alternative approach to solving my problem. Initially I didn't use "List" because I had a problem with part of my code. But it cause another problem: PlusButton not disappearing on next screen after tapping NavigationLink. This is why I wanted to use simultaneousGesture - after tapping a link some actions would be performed as well (here: PlusButton would be hidden). But it didn't work well.
I have tried an alternative solution. Using List (and maybe I will solve another problem later.
Here is my alternative code. simultaneousGesture is not needed at all. Chevrons are added automatically to the list. And PlusButton hides the same I wanted.
import SwiftUI
struct BookingView: View {
#State private var show_modal: Bool = false
var body: some View {
NavigationView {
ZStack {
List {
DateView()
.listRowInsets(EdgeInsets())
ForEach(0 ..< 12) {item in
NavigationLink(destination: BookingDetailsView()) {
HStack {
Text("Booking list item")
Spacer()
}
.padding()
}
}
}.navigationBarTitle(Text("Booking"))
VStack {
Spacer()
Button(action: {
print("Button Pushed")
self.show_modal = true
}) {
Image(systemName: "plus")
.font(.largeTitle)
.frame(width: 60, height: 60)
.foregroundColor(Color.white)
}.sheet(isPresented: self.$show_modal) {
BookingAddView()
}
.background(Color.blue)
.cornerRadius(30)
.padding()
.shadow(color: Color.black.opacity(0.3), radius: 3, x: 3, y: 3)
}
}
}
}
}