SwiftUI Mac: Adding buttonStyle Makes Button Click Propagate to Parent - swiftui

I am trying to create a situation in a SwiftUI Mac app where when I click a Button inside a parent view, only the Button's action is trigger—not any of the tap gestures attached to its parent.
Here is a simple example that reproduces the problem:
import SwiftUI
struct ContentView: View {
var body: some View {
VStack(spacing: 30){
Button("Button"){
print("button clicked")
}
.padding(5)
.background(Color.blue)
.buttonStyle(PlainButtonStyle())
}
.frame(width: 500, height: 500)
.background(Color.gray)
.padding(100)
.gesture(TapGesture(count: 2).onEnded {
//Double click (open message in popup)
print("double click")
})
.simultaneousGesture(TapGesture().onEnded {
if NSEvent.modifierFlags.contains(.command){
print("command click")
}else{
print("single click")
}
})
}
}
Clicking the button triggers both button clicked and single click.
If you comment out the buttonStyle...
//.buttonStyle(PlainButtonStyle())
It works how I want it to. Only button clicked is fired.
It doesn't seem to matter which button style I use, the behavior persists. I really need a custom button style on the child button in my situation, so how do I get around this?

If you replace your .simultaneousGesture with a regular .gesture it works for me – and still recognizes the outer single and double taps.

Related

Swiftui: How to Close one Tab in a TabView?

I'm learning SwiftUI and having trouble with closing Each Tab View Element.
My App shows photos from user's album by TabView with pageViewStyle one by one.
And What I want to make is user can click save button in each view, and when button is clicked, save that photo and close only that view while other photos are still displayed. So unless all photos are saved or discarded, if user clicks save button, TabView should automatically move to another one.
However, I don't know how to close only one Tab Element. I've tried to use dismiss() and dynamically changing vm.images element. Latter one actually works, but it displays awkward movement and it also requires quite messy code. How could I solve this issue?
Here is my code.
TabView {
ForEach(vm.images, id: \.self) { image in
TestView(image: image)
}
}
.tabViewStyle(.page(indexDisplayMode: .never))
struct TestView: View {
#ObservedObject var vm: TestviewModel
...
var body: some View {
VStack(spacing: 10) {
Image(...)
Spacer()
Button {
...
} label: {
Text("Save")
}
}
You need actually to remove saved image from the viewModel container, and UI will be updated automatically
literally
Button {
vm.images.removeAll { $0.id == image.id } // << here !!
} label: {
Text("Save")
}
You need to use the selection initializer of TabView in order to control what it displays. So replace TabView with:
TabView(selection: $selection)
Than add a new property: #State var selection: YourIdType = someDefaultValue, and in the Button action you set selection to whatever you want to display.
Also add .tag(TheIdTheViewWillUse) remember that whatever Id you use must be the same as your selection variable. I recommend you use Int for the simple use.

SwiftUI: present popover on iPhone?

I am looking at the Apple Reminders app and want to build the same pop over like view on iPhone. This the screen I am referring to:
So, I can present a popover like UI on an iPad using the popover modifier.
struct ContentView: View {
// 1.
#State var isPopoverPresented = false
var body: some View {
// 2.
Button(action: {
self.isPopoverPresented = true
}) {
Text("Some content")
}
// 3.
.popover(isPresented: $isPopoverPresented) {
Text("Popover is Presented")
.font(.largeTitle)
.frame(width: 200, height: 300)
}
}
}
However when that code runs on an iPhone, the popover turns in a fullscreen modal coming up from the bottom.
I want to know if there is a native way to build a screen like the one shown in the Reminders app or, is that screen a custom View with custom layout logic on an iPhone?
You're looking for a Menu (UIMenu in UIKit). Note that it's iOS 14+ only.

Swipe back when using a custom navigation bar and a TabView SwiftUI

I have a SwiftUI app which uses a custom navigation bar. Because of that, I need to handle the back navigation separately (both the back button and the swipe gesture). Everything went fine up until now, when I need to use a TabView to swipe between pages. The code below illustrates what I'm trying to achieve:
ContentView.swift
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
NavigationLink(destination: SecondView()) {
Text("Go to second view")
}
}
}
}
SecondView.swift
import SwiftUI
// Being able to go back by swiping
// https://stackoverflow.com/questions/59921239/hide-navigation-bar-without-losing-swipe-back-gesture-in-swiftui
extension UINavigationController: UIGestureRecognizerDelegate {
override open func viewDidLoad() {
super.viewDidLoad()
interactivePopGestureRecognizer?.delegate = self
}
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return viewControllers.count > 1
}
}
struct SecondView: View {
#Environment(\.presentationMode) var presentationMode
var body: some View {
VStack(alignment: .leading) {
Image(systemName: "chevron.left")
.foregroundColor(Color(.systemBlue))
.font(.title2)
.onTapGesture {
self.presentationMode.wrappedValue.dismiss()
}
.padding()
TabView {
Text("Test 1")
.tag(1)
Text("Test 2")
.tag(1)
Text("Test 3")
.tag(3)
}
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
}
.background(Color(.systemGray6))
.navigationBarHidden(true)
}
}
Note that I didn't add the custom navigation bar for the second view, I've just hidden the default navigation bar, as the custom bar is not needed to solve this problem.
When the user is inside the SecondView and presses the back button, everything works as expected. The problem appears when he tries to swipe back, as the swipe back gesture is captured by the TabView. I want to keep the 'swipe-between-pages' functionality of the TabView while being able to go back to ContentView when the user swipes right from the leftmost part of the screen.
This problem only appears when using TabViews, other types of content handle the swipe back gesture without problems.
To solve this problem, I could add a horizontal padding to the TabView like this:
TabView {
// content
}
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
.padding(.horizontal)
and then the user would have some space to swipe back, but this solution is not so good when some views inside the TabView need to take the whole width of the screen.
Is there any way to handle the swipe back gesture in this particular case? Maybe another possible solution would be customizing the TabView to ignore the drag gesture when the first view is presented and a swipe right gesture is captured (I don't know how to implement that).
I ran into this same problem. I solved it by wrapping my first tabview in with a geometryReader. When the bounds of that view is more than a quarter off the screen, I dismiss the view.

Swiftui navigationBarTitle beging overwritten with Preview View Text

When I go to my second page which has a ScrollView, and I scroll to the point it becomes inline and then return to the mainView - the navigationBarTitles is being overwritten with both navigationBarTitles.
I am using Xcode Version 12.5 (12E262) and this is iOS 14.
It is happening both in the simulator and on a device.
MainView
ScrollView
ScrollView scrolled so it becomes inline
And when I return to the MainView from the inline NavBar I get this.
It is fine - unless I have scrolled. And what makes it even more confusing it only does it about 25% of the time.
I am just using "self.presentationMode.wrappedValue.dismiss()" to return to the mainView
I am using a NavigationLink to go to the second page.
NavigationLink(destination: ScrollView(), isActive: $showScroll ) { EmptyView() }
Is there something I have missed when dismissing from Scrolling?
very plain code for the scrollView.
I am obviously missing something or this is a big issue with SwiftUI and Xcode.
Thank you.
var body: some View {
ScrollView(showsIndicators: false) {
}
.navigationBarBackButtonHidden(true)
.navigationBarTitle("scrollView Page")
.navigationBarItems(
leading:
Button(action:{
self.presentationMode.wrappedValue.dismiss()},
label: {
Image(systemName: "arrow.left")
})
}

Is it possible to make a modal non-dismissible in SwiftUI?

I am creating an App where the login / register part is inside a modal, which is shown if the user is not logged in.
The problem is, that the user can dismiss the modal by swiping it down...
Is it possible to prevent this?
var body: some View {
TabView(selection: $selection) {
App()
}.sheet(isPresented: self.$showSheet) { // This needs to be non-dismissible
LoginRegister()
}
}
Second example:
I am using a modal to ask for information. The user should not be able to quit this process except by dismissing the modal with save button. The user has to input information before the button works. Unfortunately the modal can be dismissed by swiping it down.
Is it possible to prevent this?
iOS 15 and later:
Use .interactiveDismissDisabled(true) on the sheet, that's all.
Prev iOS 15:
You can try to do this by using a highPriorityGesture. Of course the blue Rectangle is only for demonstration but you would have to use a view which is covering the whole screen.
struct ModalViewNoClose : View {
#Environment(\.presentationMode) var presentationMode
let gesture = DragGesture()
var body: some View {
Rectangle()
.fill(Color.blue)
.frame(width: 300, height: 600)
.highPriorityGesture(gesture)
.overlay(
VStack{
Button("Close") {
self.presentationMode.value.dismiss()
}.accentColor(.white)
Text("Modal")
.highPriorityGesture(gesture)
TextField("as", text: .constant("sdf"))
.highPriorityGesture(gesture)
} .highPriorityGesture(gesture)
)
.border(Color.green)
}
}
This is a common problem and a "code smell"... well not really code but a "design pattern smell" anyway.
The problem is that you are making your login process part of the rest of the app.
Instead of presenting the LoginRegister over the App you should really be showing either App or LoginRegister.
i.e. you should have some state object like userLoggedIn: Bool or something and depending on that value you should show either App or LoginRegister.
Just don't have both in the view hierarchy at the same time. That way your user won't be able to dismiss the view.
If you dont mind using Introspect:
import Introspect
#available(iOS 13, *)
extension View {
/// A Boolean value indicating whether the view controller enforces a modal behavior.
///
/// The default value of this property is `false`. When you set it to `true`, UIKit ignores events
/// outside the view controller's bounds and prevents the interactive dismissal of the
/// view controller while it is onscreen.
public func isModalInPresentation(_ value: Bool) -> some View {
introspectViewController {
$0.isModalInPresentation = value
}
}
}
Usage:
.sheet {
VStack {
...
}.isModalInPresentation(true)
}
iOS 15+
Starting from iOS 15 you can use interactiveDismissDisabled.
You just need to attach it to the sheet:
var body: some View {
TabView(selection: $selection) {
App()
}.sheet(isPresented: self.$showSheet) {
LoginRegister()
.interactiveDismissDisabled(true)
}
}
Regarding your second example, you can pass a variable to control when the sheet is disabled:
.interactiveDismissDisabled(!isAllInformationProvided)
You can find more information in the documentation.
theoretically this may help you (I didn't tryed it)
private var isDisplayedBind: Binding<Bool>{ Binding(get: { true }, set: { _ = $0 }) }
and usage:
content
.sheet(isPresented: isDisplayedBind) { some sheet }