Haptics have for a long time been part of the iPhone experience, so much so that SwiftUI implements them as standard in some views. In a recent tutorial about adding swipe actions for a to-do list, without planning for it, haptics were part of this thanks to SwiftUI.
For the most part you can leave the default haptics as they are because iPhone users are familiar with haptics and what they mean. If you start to change them for a swipe, then it can just add confusion. However, SwiftUI does include the ability to make some changes to them with sensoryFeedback(). We’ll take a look at these in this tutorial to see what sensoryFeedback can do.
As per the documentation, SwiftUI Views have a sensoryFeeback instance method which means that the modifier can be attached to a view, as follows:
import SwiftUI
struct ContentView: View {
@State private var count: Int = 0
@State private var triggerFeedback: Bool = false
let threshold = 5
var body: some View {
VStack(spacing: 20) {
Text("Counter: \(count)")
.font(.largeTitle)
Button("Increase") {
count += 1
if count >= threshold {
triggerFeedback.toggle()
count = 0
}
}
.buttonStyle(.borderedProminent)
.sensoryFeedback(.impact, trigger: triggerFeedback)
}
.padding()
}
}
In the example above we have a fairly simple view, that being a VStack with a nested Button and Text inside.
We start by declaring two variables that use @State property wrappers. This means that the view is refreshed each time either of those variables change.
We set a threshold of 5 which is what this counting app will count upto when haptic feedback is given.
When tapping the button, the count is incremented, and if the count is greater than or equal to the threshold, it toggles the triggerFeedback boolean and resets the count back to zero.
Line 23 is where we add in the feedback. This particular method requires the type of feedback to play, in this case the “impact”, and then has a trigger which is monitored so that it knows when the feedback needs to be played. In this example, we want an imact when the count reaches 5, at which point it is reset back to zero.
That is all there is to sensoryFeedback in this example. It is simply the type of feedback to play, and then a trigger that when it changes, triggers the feedback to occur. It doesn’t need to be a boolean. The trigger could be an array that when a change occurs, feedback is given.
Details of what other options are available for feedback can be found in the documentation here.
Leave a Reply
You must be logged in to post a comment.