How to use a ternary operator within .buttonStyle() in SwiftUI? - button

I am trying to refactor the logic o a button so I created a buttonStyle with a ternary operator inside of itself, but I am getting two errors:
Type 'ButtonStyle' has no member 'bordered'
Type 'ButtonStyle' has no member 'borderedProminent'
this is my code:
struct SelectButton: View {
#Binding var isSelecting: Bool
var body: some View{
if( isSelecting){
Button(action: {
self.isSelecting.toggle()
}, label: {
Text(isSelecting ? "Selecting" : "Select")
})
.buttonStyle(isSelecting ? .borderedProminent : .bordered)
.clipShape(RoundedRectangle(cornerRadius: 25))
}
}
}
I do not know if a struct or func -> some View is the best way to refactor.

The reason why you can't use it's because they have Mismatch types
You can either have one or the other. One is of type BorderedProminentButtonStyle while the other is of type BorderedButtonStyle
The below code shows how can achieve your result without encapsulating the entire button in a if or creating another view.
You create a View extension (this way it works for any View) then you can apply properties conditionally.
So here's the View extension
extension View {
func `if`<Content: View>(_ conditional: Bool, content: (Self) -> Content) -> TupleView<(Self?, Content?)> {
if conditional {
return TupleView((nil, content(self)))
} else {
return TupleView((self, nil))
}
}
}
The way to use it would be somewhat simple
Button(action: {
self.isSelecting.toggle()
}, label: {
Text(isSelecting ? "Selecting" : "Select")
})
.if(!isSelecting) { $0.buttonStyle(.bordered) }
.if(isSelecting) { $0.buttonStyle(.borderedProminent) }
.clipShape(RoundedRectangle(cornerRadius: 25))
I'm unsure if there's another way to compact this but I tested this on Playground and it works as expected, depending on your view it might or might not introduce bugs

Related

How to change between button styles if a condition is true in SwiftUI?

I have 2 custom button styles and I want to change the style when I tap the button. I tried this way:
Button(action: {
self.pressed.toggle()
})
{
Text("Button")
}.buttonStyle(pressed ? style1() : style2())
But it is not working, it is giving me an error from the VStack that it belongs to:
Unable to infer complex closure return type; add explicit type to disambiguate
If I do something like:
.buttonStyle(style1())
Or
.buttonStyle(style2())
Then the error goes away, so it's not from style1() or style2().
It's swift type-checking violation... I would recommend instead
Button(action: {
self.pressed.toggle()
})
{
Text("Button")
}.buttonStyle(Your_style(condition: pressed)) // << put conditional styling inside
See for example solution in Change buttonStyle Modifier based on light or dark mode in SwiftUI
You can create a useful extension like below
extension View {
func conditionalModifier<M1: ViewModifier, M2: ViewModifier>
(on condition: Bool, trueCase: M1, falseCase: M2) -> some View {
Group {
if condition {
self.modifier(trueCase)
} else {
self.modifier(falseCase)
}
}
}
func conditionalModifier<M: ViewModifier>
(on condition: Bool, trueCase: M) -> some View {
Group {
if condition {
self.modifier(trueCase)
}
}
}
}
Usage;
#State var condition = false
var body: some View {
Text("conditional modifier")
// Apply style if condition is true, otherwise do nothing
.conditionalModifier(on: condition, trueCase: Style1())
// Decision between 2 style
.conditionalModifier(on: condition, trueCase: Style1(), falseCase: Style2())
}

How to pass a parameter to the action of Button with SwiftUI

I would like to change the language in my app, in order to do that I want to use Buttons.
So for each language I will have a Button, which will pass a parameter with the language code of that language.
Now I know it is possible to pass a function to a Button but how to pass a function with a Parameter?
To pass parameters to the action, I think there are multiple ways to do so. But I found this the most elegant way of doing it.
First of all I create a function which accepts a parameter "language". Then that function will return an anonymous function which uses the "language" parameter:
func changeLanguage(language: String) -> () -> () {
return {
print(language)
}
}
In the view I can create Buttons which will hold the anonymous function which is being returned by "changeLanguage" with a "language" parameter that can differ per Button.
var body: some View {
List {
Section(header: Text(NSLocalizedString("Language", comment: "settings.view.select.language"))) {
Button(NSLocalizedString("English", comment: "settings.view.language.english"), action: self.changeLanguage(language: "en"))
Button(NSLocalizedString("Dutch", comment: "settings.view.language.dutch"), action: self.changeLanguage(language: "nl"))
}
}
.listStyle(GroupedListStyle())
}
You can use a closure calling a method with your parameter, like this:
import SwiftUI
struct LanguageView: View {
var body: some View {
Button(action: { selectLanguage(language: "en") }) {
Text("English")
}
}
func selectLanguage(language: String) {
print("Language selected: \(language)")
}
}

SwiftUI: how to handle BOTH tap & long press of button?

I have a button in SwiftUI and I would like to be able to have a different action for "tap button" (normal click/tap) and "long press".
Is that possible in SwiftUI?
Here is the simple code for the button I have now (handles only the "normal" tap/touch case).
Button(action: {self.BLEinfo.startScan() }) {
Text("Scan")
} .disabled(self.BLEinfo.isScanning)
I already tried to add a "longPress gesture" but it still only "executes" the "normal/short" click. This was the code I tried:
Button(action: {self.BLEinfo.startScan() }) {
Text("Scan")
.fontWeight(.regular)
.font(.body)
.gesture(
LongPressGesture(minimumDuration: 2)
.onEnded { _ in
print("Pressed!")
}
)
}
Thanks!
Gerard
I tried many things but finally I did something like this:
Button(action: {
}) {
VStack {
Image(self.imageName)
.resizable()
.onTapGesture {
self.action(false)
}
.onLongPressGesture(minimumDuration: 0.1) {
self.action(true)
}
}
}
It is still a button with effects but short and long press are different.
Combining a high priority gesture and a simultaneous gesture should do the trick.
Button(action: {})
{
Text("A Button")
}
.simultaneousGesture(
LongPressGesture()
.onEnded { _ in
print("Loooong")
}
)
.highPriorityGesture(TapGesture()
.onEnded { _ in
print("Tap")
})
Found this a handy pattern when interacting with other views as well.
I just discovered that the effect depends on the order of the implementation. Implementing the detection of gestures in the following order it seems to be possible to detect and identify all three gestures:
handle a double tap gesture
handle a longPressGesture
handle a single tap gesture
Tested on Xcode Version 11.3.1 (11C504)
fileprivate func myView(_ height: CGFloat, _ width: CGFloat) -> some View {
return self.textLabel(height: height, width: width)
.frame(width: width, height: height)
.onTapGesture(count: 2) {
self.action(2)
}
.onLongPressGesture {
self.action(3)
}
.onTapGesture(count: 1) {
self.action(1)
}
}
Here is my implementation using a modifier:
struct TapAndLongPressModifier: ViewModifier {
#State private var isLongPressing = false
let tapAction: (()->())
let longPressAction: (()->())
func body(content: Content) -> some View {
content
.scaleEffect(isLongPressing ? 0.95 : 1.0)
.onLongPressGesture(minimumDuration: 1.0, pressing: { (isPressing) in
withAnimation {
isLongPressing = isPressing
print(isPressing)
}
}, perform: {
longPressAction()
})
.simultaneousGesture(
TapGesture()
.onEnded { _ in
tapAction()
}
)
}
}
Use it like this on any view:
.modifier(TapAndLongPressModifier(tapAction: { <tap action> },
longPressAction: { <long press action> }))
It just mimics the look a button by scaling the view down a bit. You can put any other effect you want after scaleEffect to make it look how you want when pressed.
I had to do this for an app I am building, so just wanted to share. Refer code at the bottom, it is relatively self explanatory and sticks within the main elements of SwiftUI.
The main differences between this answer and the ones above is that this allows for updating the button's background color depending on state and also covers the use case of wanting the action of the long press to occur once the finger is lifted and not when the time threshold is passed.
As noted by others, I was unable to directly apply gestures to the Button and had to apply them to the Text View inside it. This has the unfortunate side-effect of reducing the 'hitbox' of the button, if I pressed near the edges of the button, the gesture would not fire. Accordingly I removed the Button and focused on manipulating my Text View object directly (this can be replaced with Image View, or other views (but not Button!)).
The below code sets up three gestures:
A LongPressGesture that fires immediately and reflects the 'tap' gesture in your question (I haven't tested but this may be able to replaced with the TapGesture)
Another LongPressGesture that has a minimum duration of 0.25 and reflect the 'long press' gesture in your question
A drag gesture with minimum distance of 0 to allow us to do events at the end of our fingers lifting from the button and not automatically at 0.25 seconds (you can remove this if this is not your use case). You can read more about this here: How do you detect a SwiftUI touchDown event with no movement or duration?
We sequence the gestures as follows: Use 'Exclusively' to combine the "Long Press" (i.e. 2 & 3 above combined) and Tap (first gesture above), and if the 0.25 second threshold for "Long Press" is not reached, the tap gesture is executed. The "Long Press" itself is a sequence of our long press gesture and our drag gesture so that the action is only performed once our finger is lifted up.
I also added code in the below for updating the button's colours depending on the state. One small thing to note is that I had to add code on the button's colour into the onEnded parts of the long press and drag gesture because the minuscule processing time would unfortunately result in the button switching back to darkButton colour between the longPressGesture and the DragGesture (which should not happen theoretically, unless I have a bug somewhere!).
You can read more here about Gestures: https://developer.apple.com/documentation/swiftui/gestures/composing_swiftui_gestures
If you modify the below and pay attention to Apple's notes on Gestures (also this answer was useful reading: How to fire event handler when the user STOPS a Long Press Gesture in SwiftUI?) you should be able to set up complex customised button interactions. Use the gestures as building blocks and combine them to remove any deficiency within individual gestures (e.g. longPressGesture does not have an option to do the events at its end and not when the condition is reached).
P.S. I have a global environment object 'dataRouter' (which is unrelated to the question, and just how I choose to share parameters across my swift views), which you can safely edit out.
struct AdvanceButton: View {
#EnvironmentObject var dataRouter: DataRouter
#State var width: CGFloat
#State var height: CGFloat
#State var bgColor: Color
#GestureState var longPress = false
#GestureState var longDrag = false
var body: some View {
let longPressGestureDelay = DragGesture(minimumDistance: 0)
.updating($longDrag) { currentstate, gestureState, transaction in
gestureState = true
}
.onEnded { value in
print(value.translation) // We can use value.translation to see how far away our finger moved and accordingly cancel the action (code not shown here)
print("long press action goes here")
self.bgColor = self.dataRouter.darkButton
}
let shortPressGesture = LongPressGesture(minimumDuration: 0)
.onEnded { _ in
print("short press goes here")
}
let longTapGesture = LongPressGesture(minimumDuration: 0.25)
.updating($longPress) { currentstate, gestureState, transaction in
gestureState = true
}
.onEnded { _ in
self.bgColor = self.dataRouter.lightButton
}
let tapBeforeLongGestures = longTapGesture.sequenced(before:longPressGestureDelay).exclusively(before: shortPressGesture)
return
Text("9")
.font(self.dataRouter.fontStyle)
.foregroundColor(self.dataRouter.darkButtonText)
.frame(width: width, height: height)
.background(self.longPress ? self.dataRouter.lightButton : (self.longDrag ? self.dataRouter.brightButton : self.bgColor))
.cornerRadius(15)
.gesture(tapBeforeLongGestures)
}
}
This isn't tested, but you can try to add a LongPressGesture to your button.
It'll presumably look something like this.
struct ContentView: View {
#GestureState var isLongPressed = false
var body: some View {
let longPress = LongPressGesture()
.updating($isLongPressed) { value, state, transaction in
state = value
}
return Button(/*...*/)
.gesture(longPress)
}
}
Kevin's answer was the closest to what I needed. Since ordering the longPressGesture before the tapGesture broke ScrollViews for me, but the inverse made the minimumDuration parameter do nothing, I implemented the long press functionality myself:
struct TapAndLongPressModifier: ViewModifier {
#State private var canTap = false
#State private var pressId = 0
let tapAction: (()->())
let longPressAction: (()->())
var minimumDuration = 1.0
func body(content: Content) -> some View {
content
.onTapGesture {
if canTap {
tapAction()
}
}
.onLongPressGesture(
minimumDuration: 1.0,
pressing: { (isPressing) in
pressId += 1
canTap = isPressing
if isPressing {
let thisId = pressId
DispatchQueue.main.asyncAfter(deadline: .now() + minimumDuration) {
if thisId == pressId {
canTap = false
longPressAction()
}
}
}
},
// We won't actually use this
perform: {}
)
}
}
just do this:
the first modifier should be onLongPressGesture(minumumDuration: (the duration you want))
and the following mondifier should be onLongPressGesture(minimumDuration: 0.01) <- or some other super small numbers
this works for me perfectly
As a follow up, I had the same issue and I tried all of these answers but didn't like how they all worked.
I ended up using a .contextMenu it was way easier and produces pretty much the same effect.
Check link here
and here is an example
UPDATE:
As of iOS 16, .contextMenu has been depreciated. So I ended up using .simultaneousGesture on the Button, not the content in the button's label block.
i.e.
Button {
// handle Button Tap
} label: {
// button label content here
}
.simultaneousGesture(LongPressGesture()
.onEnded { _ in
// handle long press here
}
)
This still preserves the button animations as well.
Note tested before iOS 16 however.
Thought I'd post back on this, in case anyone else is struggling. Strange that Apple's default behaviour works on most controls but not buttons. In my case I wanted to keep button effects while supporting long press.
An approach that works without too much complexity is to ignore the default button action and create a simultaneous gesture that handles both normal and long clicks.
In your view you can apply a custom long press modifier like this:
var body: some View {
// Apply the modifier
Button(action: self.onReloadDefaultAction) {
Text("Reload")
}
.modifier(LongPressModifier(
isDisabled: self.sessionButtonsDisabled,
completionHandler: self.onReloadPressed))
}
// Ignore the default click
private func onReloadDefaultAction() {
}
// Handle the simultaneous gesture
private func onReloadPressed(isLongPress: Bool) {
// Do the work here
}
My long press modifier implementation looked like this and uses the drag gesture that I found from another post. Not very intuitive but it works reliably, though of course I would prefer not to have to code this plumbing myself.
struct LongPressModifier: ViewModifier {
// Mutable state
#State private var startTime: Date?
// Properties
private let isDisabled: Bool
private let longPressSeconds: Double
private let completionHandler: (Bool) -> Void
// Initialise long press behaviour to 2 seconds
init(isDisabled: Bool, completionHandler: #escaping (Bool) -> Void) {
self.isDisabled = isDisabled
self.longPressSeconds = 2.0
self.completionHandler = completionHandler
}
// Capture the start and end times
func body(content: Content) -> some View {
content.simultaneousGesture(DragGesture(minimumDistance: 0)
.onChanged { _ in
if self.isDisabled {
return
}
// Record the start time at the time we are clicked
if self.startTime == nil {
self.startTime = Date()
}
}
.onEnded { _ in
if self.isDisabled {
return
}
// Measure the time elapsed and reset
let endTime = Date()
let interval = self.startTime!.distance(to: endTime)
self.startTime = nil
// Return a boolean indicating whether a normal or long press
let isLongPress = !interval.isLess(than: self.longPressSeconds)
self.completionHandler(isLongPress)
})
}
}
Try this :)
Handles isInactive, isPressing, isLongPress and Tap(Click)
based on this
I tried to make this as a viewmodifier without success. I would like to see an example with #GestureState variable wrapper used in same manner as #State/#Published are bound to #Binding in view components.
Tested: Xcode 12.0 beta, macOS Big Sur 11.0 beta
import SwiftUI
enum PressState {
case inactive
case pressing
case longPress
var isPressing: Bool {
switch self {
case .inactive:
return false
case .pressing, .longPress:
return true
}
}
var isLongPress: Bool {
switch self {
case .inactive, .pressing:
return false
case .longPress:
return true
}
}
var isInactive : Bool {
switch self {
case .inactive:
return true
case .pressing, .longPress:
return false
}
}
}
struct ContentView: View {
#GestureState private var pressState: PressState = PressState.inactive
#State var showClick: Bool = false
var press: some Gesture {
LongPressGesture(minimumDuration: 0.8, maximumDistance: 50.0)
.sequenced(before: LongPressGesture(minimumDuration: .infinity, maximumDistance: 50.0))
.updating($pressState) { value, state, transaction in
switch value {
case .first(true): // first gesture starts
state = PressState.pressing
case .second(true, nil): // first ends, second starts
state = PressState.longPress
default: break
}
}
}
var body: some View {
ZStack{
Group {
Text("Click")
.offset(x: 0, y: pressState.isPressing ? (pressState.isLongPress ? -120 : -100) : -40)
.animation(Animation.linear(duration: 0.5))
.opacity(showClick ? 1 : 0 )
.animation(Animation.linear(duration: 0.3))
Text("Pressing")
.opacity(pressState.isPressing ? 1 : 0 )
.offset(x: 0, y: pressState.isPressing ? (pressState.isLongPress ? -100 : -80) : -20)
.animation(Animation.linear(duration: 0.5))
Text("Long press")
.opacity(pressState.isLongPress ? 1 : 0 )
.offset(x: 0, y: pressState.isLongPress ? -80 : 0)
.animation(Animation.linear(duration: 0.5))
}
Group{
Image(systemName: pressState.isLongPress ? "face.smiling.fill" : (pressState.isPressing ? "circle.fill" : "circle"))
.offset(x: 0, y: -100)
.font(.system(size: 60))
.opacity(pressState.isLongPress ? 1 : (pressState.isPressing ? 0.6 : 0.2))
.foregroundColor(pressState.isLongPress ? .orange : (pressState.isPressing ? .yellow : .white))
.rotationEffect(.degrees(pressState.isLongPress ? 360 : 0), anchor: .center)
.animation(Animation.linear(duration: 1))
Button(action: {
showClick = true
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
self.showClick = false
})
}, label: {
ZStack {
Circle()
.fill(self.pressState.isPressing ? Color.blue : Color.orange)
.frame(width: 100, height: 100, alignment: .center)
Text("touch me")
}}).simultaneousGesture(press)
}.offset(x: 0, y: 110)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

How do you make a Button conditionally hidden or disabled?

How do I toggle the presence of a button to be hidden or not?
We have the non-conditional .hidden() property; but I need the conditional version.
Note: we do have the .disabled(bool) property available, but not the .hidden(bool).
struct ContentView: View {
var body: some View {
ZStack {
Color("SkyBlue")
VStack {
Button("Detect") {
self.imageDetectionVM.detect(self.selectedImage)
}
.padding()
.background(Color.orange)
.foreggroundColor(Color.white)
.cornerRadius(10)
.hidden() // ...I want this to be toggled.
}
}
}
}
I hope hidden modifier gets argument later, but since then, Set the alpha instead:
#State var shouldHide = false
var body: some View {
Button("Button") { self.shouldHide = true }
.opacity(shouldHide ? 0 : 1)
}
For me it worked perfectly to set the frame's height to zero when you do not want to see it. When you want to have the calculated size, just set it to nil:
SomeView
.frame(height: isVisible ? nil : 0)
If you want to disable it in addition to hiding it, you could set .disabled with the toggled boolean.
SomeView
.frame(height: isVisible ? nil : 0)
.disabled(!isVisible)
You can utilize SwiftUI's new two-way bindings and add an if-statement as:
struct ContentView: View {
#State var shouldHide = false
var body: some View {
ZStack {
Color("SkyBlue")
VStack {
if !self.$shouldHide.wrappedValue {
Button("Detect") {
self.imageDetectionVM.detect(self.selectedImage)
}
.padding()
.background(Color.orange)
.foregroundColor(Color.white)
.cornerRadius(10)
}
}
}
}
}
The benefit of doing this over setting the opacity to 0 is that it will remove the weird spacing/padding from your UI caused from the button still being in the view, just not visible (if the button is between other view components, that is).
all the answers here works specifically for a button to be hidden conditionally.
What i think might help is making a modifier itself conditionally e.g:
.hidden for button/view, or maybe .italic for text, etc..
Using extensions.
For text to be conditionally italic it is easy since .italic modifier returns Text:
extension Text {
func italicConditionally(isItalic: Bool) -> Text {
isItalic ? self.italic() : self
}
}
then applying conditional italic like this:
#State private var toggle = false
Text("My Text")
.italicConditionally(isItalic: toggle)
However for Button it is tricky, since the .hidden modifier returns "some view":
extension View {
func hiddenConditionally(isHidden: Bool) -> some View {
isHidden ? AnyView(self.hidden()) : AnyView(self)
}
}
then applying conditional hidden like this:
#State private var toggle = false
Button("myButton", action: myAction)
.hiddenConditionally(isHidden: toggle)
You can easily hide a view in SwiftUI using a conditional statement.
struct TestView: View{
#State private var isVisible = false
var body: some View{
if !isVisible {
HStack{
Button(action: {
isVisible.toggle()
// after click you'r view will be hidden
}){
Text("any view")
}
}
}
}
}
It isn't always going to be a pretty solution, but in some cases, adding it conditionally may also work:
if shouldShowMyButton {
Button(action: {
self.imageDetectionVM.detect(self.selectedImage)
}) {
Text("Button")
}
}
There will be an issue of the empty space in the case when it isn't being shown, which may be more or less of an issue depending on the specific layout. That might be addressed by adding an else statement that alternatively adds an equivalently sized blank space.
#State private var isHidden = true
VStack / HStack
if isHidden {
Button {
if !loadVideo(),
let urlStr = drill?.videoURL as? String,
let url = URL(string: urlStr) {
player = VideoPlayerView(player: AVPlayer(), videoUrl: url)
playVideo.toggle()
}
} label: {
Image(playVideo ? "ic_close_blue" : "ic_video_attached")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 50)
}
.buttonStyle(BorderlessButtonStyle())
}
.onAppear {
if shouldShowButton {
isHidden = false
} else {
isVideoButtonHidden = true
}
}

How do I use TextInput for WatchOS in swiftUI

Typically I would use presentTextInputControllerWithSuggestions() to show the TextInput field. But this isn't available in swiftUI because it is a function of WKInterfaceController. Do I have to use the WKInterfaceController for this?
I couldn't find anything in the documentation.
You can use extension for View in SwiftUI:
extension View {
typealias StringCompletion = (String) -> Void
func presentInputController(withSuggestions suggestions: [String], completion: #escaping StringCompletion) {
WKExtension.shared()
.visibleInterfaceController?
.presentTextInputController(withSuggestions: suggestions,
allowedInputMode: .plain) { result in
guard let result = result as? [String], let firstElement = result.first else {
completion("")
return
}
completion(firstElement)
}
}
}
Example:
struct ContentView: View {
var body: some View {
Button(action: {
presentInputController()
}, label: {
Text("Press this button")
})
}
private func presentInputController() {
presentInputController(withSuggestions: []) { result in
// handle result from input controller
}
}
}
This would be done through a TextField in SwiftUI.

Resources