SwiftUI onDrag preview doesn't get updated when Image changes on macOS - macos

I'm having an .onDrag on an Image. Whether I provide a preview myself or not, the preview always gets stuck to show the Image that appeared on the first drag. The NSItemProvider itself works well and I access the proper data, but not within the preview.
A simple example (code available here: https://github.com/godbout/DragPreview)
import SwiftUI
struct AppDetail {
let bundleIdentifier: String
let icon: NSImage
init(bundleIdentifier: String) {
self.bundleIdentifier = bundleIdentifier
if
let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier),
let representation = NSWorkspace.shared.icon(forFile: url.path).bestRepresentation(for: NSRect(x: 0, y: 0, width: 64, height: 64), context: nil, hints: nil)
{
self.icon = NSImage(size: representation.size)
self.icon.addRepresentation(representation)
} else {
self.icon = NSApp.applicationIconImage!
}
}
}
struct ContentView: View {
#State private var apps: [AppDetail] = [
AppDetail(bundleIdentifier: "com.apple.Mail"),
AppDetail(bundleIdentifier: "com.apple.MobileSMS"),
AppDetail(bundleIdentifier: "com.apple.Safari"),
]
var body: some View {
VStack(alignment: .center) {
Image(nsImage: apps.first == nil ? NSApp.applicationIconImage! : apps.first!.icon)
.onDrag {
guard
let app = apps.first,
let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: app.bundleIdentifier)
else {
return NSItemProvider()
}
return NSItemProvider(object: url as NSURL)
} preview: {
Text(apps.first == nil ? "no app" : apps.first!.bundleIdentifier)
Image(nsImage: apps.first == nil ? NSApp.applicationIconImage! : apps.first!.icon)
}
Button("next") {
apps.removeFirst()
}
.disabled(apps.isEmpty)
}
.frame(width: 200, height: 200)
.padding()
}
}
Anything I'm doing wrong? Could this be a(nother) SwiftUI bug? If the preview is actually static and only rendered at the first drag, how could I change the code so that I get the preview of my current Image?
Thanks.

I read somewhere in a comment by #Asperi that the drag preview is only created once at init. So if you add an .id to the image it forces a redraw and reinit of preview:
Image(nsImage: apps.first == nil ? NSApp.applicationIconImage! : apps.first!.icon)
.id(apps.first?.bundleIdentifier) // here
.onDrag { ...

Related

View Modifier messing with animations

I've been looking to add a loading indicator to my project, and found a really cool animation here. To make it easier to use, I wanted to incorporate it into a view modifier to put it on top of the current view. However, when I do so, it doesn't animate when I first press the button. I have played around with it a little, and my hypothesis is that the View Modifier doesn't pass the initial isAnimating = false, so only passes it isAnimating = true when the button is pressed. Because the ArcsAnimationView doesn't get the false value initially, it doesn't actually animate anything and just shows the static arcs. However, if I press the button a second time afterwards, it seems to be initialized and the view properly animates as desired.
Is there a better way to structure my code to avoid this issue? Am I missing something key? Any help is greatly appreciated.
Below is the complete code:
import SwiftUI
struct ArcsAnimationView: View {
#Binding var isAnimating: Bool
let count: UInt = 4
let width: CGFloat = 5
let spacing: CGFloat = 2
init(isAnimating: Binding<Bool>) {
self._isAnimating = isAnimating
}
var body: some View {
GeometryReader { geometry in
ForEach(0..<Int(count)) { index in
item(forIndex: index, in: geometry.size)
// the rotation below is what is animated ...
// I think the problem is that it just starts at .degrees(360), instead of
// .degrees(0) as expected, where it is then animated to .degrees(360)
.rotationEffect(isAnimating ? .degrees(360) : .degrees(0))
.animation(
Animation.default
.speed(Double.random(in: 0.05...0.25))
.repeatCount(isAnimating ? .max : 1, autoreverses: false)
, value: isAnimating
)
.foregroundColor(Color(hex: AppColors.darkBlue1.rawValue))
}
}
.aspectRatio(contentMode: .fit)
}
private func item(forIndex index: Int, in geometrySize: CGSize) -> some View {
Group { () -> Path in
var p = Path()
p.addArc(center: CGPoint(x: geometrySize.width/2, y: geometrySize.height/2),
radius: geometrySize.width/2 - width/2 - CGFloat(index) * (width + spacing),
startAngle: .degrees(0),
endAngle: .degrees(Double(Int.random(in: 120...300))),
clockwise: true)
return p.strokedPath(.init(lineWidth: width))
}
.frame(width: geometrySize.width, height: geometrySize.height)
}
}
struct ArcsAnimationModifier: ViewModifier {
#Binding var isAnimating: Bool
func body(content: Content) -> some View {
ZStack {
if isAnimating {
ArcsAnimationView(isAnimating: _isAnimating)
.frame(width: 150)
}
content
.disabled(isAnimating)
}
}
}
extension View {
func loadingAnimation(isAnimating: Binding<Bool>) -> some View {
self.modifier(ArcsAnimationModifier(isAnimating: isAnimating))
}
}
Here is where I actually call the function:
struct AnimationView: View {
#State var isAnimating = false
var body: some View {
VStack {
Button(action: {
self.isAnimating = true
DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
self.isAnimating = false
}
}, label: {
Text("show animation")
})
}
.loadingAnimation(isAnimating: $isAnimating)
}
}
Note: I am fairly certain the issue is with View Modifier since if I call ArcsAnimationView as a regular view in AnimationView, it works as expected.
I get there to see some implementation, but I think others would prefer a simple base to start from.
here my 2 cents to show how to write an AnimatableModifier that can be used on multiple objects cleaning up ".animation" in code.
struct ContentView: View {
#State private var hideWhilelUpdating = false
var body: some View {
Image(systemName: "tshirt.fill")
.modifier(SmoothHideAndShow(hide: hideWhilelUpdating))
Text("Some contents to show...")
.modifier(SmoothHideAndShow(hide: hideWhilelUpdating))
Button( "hide and show smootly") {
hideWhilelUpdating.toggle()
}
.padding(60)
}
}
struct SmoothHideAndShow: AnimatableModifier {
var hide: Bool
var animatableData: CGFloat {
get { CGFloat(hide ? 0 : 1) }
set { hide = newValue == 0 }
}
func body(content: Content) -> some View {
content
.opacity(hide ? 0.2 : 1)
.animation(.easeIn(duration: 1), value: hide)
}
}
when pressing button, our bool will trigger animation that fades in and out our text.
I use it during network calls (omitted for clarity... and replaced with button) to hide values under remote update. When network returns, I toggle boolean.

How to open new window on second screen (second display)

The task is simple, but I don't know where to start looking for any pointers on MacOs App development with two displays. I'm building a presenter app where the main app will be displaying on the primary display and with the push of a button I need to push a fullscreen window onto the second display or second monitor. How would I go about doing this? I am using SwiftUI, but am open to other suggestions.
After a bit of tinkering around I came across this solution which I modified to make it work for me. Add the following extension.
extension View {
private func newWindowInternal(with title: String) -> NSWindow {
let window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 0, height: 0),
styleMask: [.closable, .borderless],
backing: .buffered,
defer: false)
guard let secondScreen = NSScreen.screens.last else {
print("Failed to find last display")
return window
}
window.setFrame(secondScreen.frame, display: true)
window.level = NSWindow.Level.screenSaver
window.isReleasedWhenClosed = false
window.title = title
window.orderFront(nil)
return window
}
func openNewWindow(with title: String = "new Window") {
self.newWindowInternal(with: title).contentView = NSHostingView(rootView: self)
}
}
In your ContentView, add a button which will trigger the activation of the new window. Here's an example ContentView
struct ContentView: View {
#State private var windowOpened = false
var body: some View {
VStack {
Button("Open window") {
if !windowOpened {
ProjectorView(isOpen: $windowOpened).openNewWindow(with: "Projector")
}
}
.keyboardShortcut("o", modifiers: [.option, .command])
Button("Close window") {
NSApplication.shared.windows.first(where: { $0.title == "Projector" })?.close()
}
.keyboardShortcut("w", modifiers: [.option, .command])
}
.frame(width: 300, height: 100)
}
}
Finally, here's what ProjectorView looks like.
struct ProjectorView: View {
#Binding var isOpen: Bool
var body: some View {
HStack {
Spacer()
VStack {
Spacer()
Text("Hello World!")
.font(.title2)
Spacer()
}
Spacer()
}
.padding()
.onDisappear {
isOpen = false
}
.onAppear {
isOpen = true
}
}
}
This solution works great. Pressing ⌥⌘O will open ProjectorView on the second screen above all other windows and pressing ⌥⌘W will close ProjectorView window. Window settings, and window level can be tweaked in the extension.
Tested on macOS Monterey, Xcode 13, Apple M1 MacBook Air.

SwiftUI How to get the view size for a custom slide transition?

SwiftUI has the default slide transition .transition(.slide). It works well, but only halfway. I mean, I have to slide my views and then slide them back (I need the animation backwards). Since it is not possible to set the direction of the slide transition, I implemented a custom transition. The implementation is simple enough and works well. But I can't get the view size to calculate the start and end offset points.
extension AnyTransition {
static func slide(direction: SlideModifier.Direction) -> AnyTransition {
.asymmetric(insertion: .modifier(active: SlideModifier(positiveOffset: true, direction: direction), identity: SlideModifier(positiveOffset: nil, direction: direction)),
removal: .modifier(active: SlideModifier(positiveOffset: false, direction: direction), identity: SlideModifier(positiveOffset: nil, direction: direction)))
}
}
internal struct SlideModifier: ViewModifier {
let positiveOffset: Bool?
let direction: Direction
let offsetSize: CGFloat = 200 // How can I get this value programmatically?
enum Direction {
case leading, top, trailing, bottom
}
func body(content: Content) -> some View {
switch direction {
case .leading:
return content.offset(x: positiveOffset == nil ? 0 : (positiveOffset! ? offsetSize : -offsetSize))
case .top:
return content.offset(y: positiveOffset == nil ? 0 : (positiveOffset! ? offsetSize : -offsetSize))
case .trailing:
return content.offset(x: positiveOffset == nil ? 0 : (positiveOffset! ? -offsetSize : offsetSize))
case .bottom:
return content.offset(y: positiveOffset == nil ? 0 : (positiveOffset! ? -offsetSize : offsetSize))
}
}
}
I want to define the offset size that is equal to the view size. My experiments have shown that this is how the standard slide transition works. I tried using GeometryReader and PreferenceKey to get the size. Maybe I did something wrong, but it didn't work.
Here's a simple example of using my custom transition.
struct ContentView: View {
#State private var isShowingRed = false
var body: some View {
ZStack {
if isShowingRed {
Color.red
.frame(width: 200, height: 200)
.transition(.slide(direction: .trailing))
} else {
Color.blue
.frame(width: 200, height: 200)
.transition(.slide(direction: .leading))
}
}
.onTapGesture {
withAnimation {
isShowingRed.toggle()
}
}
}
}
There are a few ways to get the size of a view. In your case I'm assuming you're looking for the screen size. Here are the methods to get that. Please bear in mind I don't have my IDE open to fully test this, there may be syntax issues in it. I'll update my answer later when I have my IDE open.
Hot Tip
Get used to using an in-line condition, it'll help tremendously when dealing with animations and views in Swift UI
someBool ? varIfTrue : varIfFalse
someValue == someTest ? varIfTrue : varIfFalse
//(boolCondition) ? (Value if True) : (Value If False)
//You can even chain them together, but be careful to keep it
//organized if you do this.
someBool ? someBool2 ? val1 : val2 : someBool2 ? val3 : val4
Raw Screen Size
Nice Extension Provided Here
var width = UIScreen.main.bounds.size.width
var height = UIScreen.main.bounds.size.height
Geometry Reader
This one is a bit more confusing because it will get the VIEW that it is in. It also has a property that you can set to ignore safe areas. If you use this method you'll get different responses based on the view.
//Parent Views Matter with GeometryReader
var body: some View {
GeometryReader { geometry in
//Use the geometry, full screen size.
}.ignoresSafeAreaAndEdges(.all)
}
var body: someView {
VStack {
GeometryReader { geometry in
//This will have only the size of the parent view.
// Ex: 100x100 square.
}
}.frame(width: 100, height: 100)
}
Animating Backwards
The way that you're animating works, however doing it this way will give you a "Rewind" type effect.
var body: some View {
ZStack {
if isShowingRed {
Color.red
.frame(width: 200, height: 200)
.offset(isShowingRed ? 0 : 100)
.animation(.spring()) //You can also use .default
} else {
Color.blue
.frame(width: 200, height: 200)
.offset(isShowingRed ? 100 : 0)
.animation(.spring()) //You can also use .default
}
}
.onTapGesture {
withAnimation {
isShowingRed.toggle()
}
}
}

SwiftUI 2.0 TabView disable swipe to change page

I have a TabView thats using the swiftUI 2.0 PageTabViewStyle. Is there any way to disable the swipe to change pages?
I have a search bar in my first tab view, but if a user is typing, I don't want to give the ability to change they are on, I basically want it to be locked on to that screen until said function is done.
Here's a gif showing the difference, I'm looking to disable tab changing when it's full screen in the gif.
https://imgur.com/GrqcGCI
Try something like the following (tested with some stub code). The idea is to block tab view drag gesture when some condition (in you case start editing) happens
#State var isSearching = false
// ... other code
TabView {
// ... your code here
Your_View()
.gesture(isSearching ? DragGesture() : nil) // blocks TabView gesture !!
}
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .always))
I tried Asperis's solution, but I still couldn't disable the swiping, and adding disabled to true didn't work since I want the child views to be interactive. The solution that worked for me was using Majid's (https://swiftwithmajid.com/2019/12/25/building-pager-view-in-swiftui/) custom Pager View and adding a conditional like Asperi's solution.
Majid's PagerView with conditional:
import SwiftUI
struct PagerView<Content: View>: View {
let pageCount: Int
#Binding var canDrag: Bool
#Binding var currentIndex: Int
let content: Content
init(pageCount: Int, canDrag: Binding<Bool>, currentIndex: Binding<Int>, #ViewBuilder content: () -> Content) {
self.pageCount = pageCount
self._canDrag = canDrag
self._currentIndex = currentIndex
self.content = content()
}
#GestureState private var translation: CGFloat = 0
var body: some View {
GeometryReader { geometry in
HStack(spacing: 0) {
self.content.frame(width: geometry.size.width)
}
.frame(width: geometry.size.width, alignment: .leading)
.offset(x: -CGFloat(self.currentIndex) * geometry.size.width)
.offset(x: self.translation)
.animation(.interactiveSpring(), value: currentIndex)
.animation(.interactiveSpring(), value: translation)
.gesture(!canDrag ? nil : // <- here
DragGesture()
.updating(self.$translation) { value, state, _ in
state = value.translation.width
}
.onEnded { value in
let offset = value.translation.width / geometry.size.width
let newIndex = (CGFloat(self.currentIndex) - offset).rounded()
self.currentIndex = min(max(Int(newIndex), 0), self.pageCount - 1)
}
)
}
}
}
ContentView:
import SwiftUI
struct ContentView: View {
#State private var currentPage = 0
#State var canDrag: Bool = true
var body: some View {
PagerView(pageCount: 3, canDrag: $canDrag, currentIndex: $currentPage) {
VStack {
Color.blue
Button {
canDrag.toggle()
} label: {
Text("Toogle drag")
}
}
VStack {
Color.red
Button {
canDrag.toggle()
} label: {
Text("Toogle drag")
}
}
VStack {
Color.green
Button {
canDrag.toggle()
} label: {
Text("Toogle drag")
}
}
}
}
}
Ok I think it is possible to block at least 99% swipe gesture if not 100% by using this steps:
and 2.
Add .gesture(DragGesture()) to each page
Add .tabViewStyle(.page(indexDisplayMode: .never))
SwiftUI.TabView(selection: $viewModel.selection) {
ForEach(pages.indices, id: \.self) { index in
pages[index]
.tag(index)
.gesture(DragGesture())
}
}
.tabViewStyle(.page(indexDisplayMode: .never))
Add .highPriorityGesture(DragGesture()) to all remaining views images, buttons that still enable to drag and swipe pages
You can also in 1. use highPriorityGesture but it completely blocks drags on each pages, but I need them in some pages to rotate something
For anyone trying to figure this out, I managed to do this by setting the TabView state to disabled.
TabView(selection: $currentIndex.animation()) {
Items()
}.disabled(true)
Edit: as mentioned in the comments this will disable everything within the TabView as well

Is it possible to change image with fade animation using same Image? (SwiftUI)

According to my logic, on tap gesture to the image it should be changed with fade animation, but actual result is that image changes without animation. Tested with Xcode 11.3.1, Simulator 13.2.2/13.3 if it is important.
P.S. Images are named as "img1", "img2", "img3", etc.
enum ImageEnum: String {
case img1
case img2
case img3
func next() -> ImageEnum {
switch self {
case .img1: return .img2
case .img2: return .img3
case .img3: return .img1
}
}
}
struct ContentView: View {
#State private var img = ImageEnum.img1
var body: some View {
Image(img.rawValue)
.onTapGesture {
withAnimation {
self.img = self.img.next()
}
}
}
}
Update: re-tested with Xcode 13.3 / iOS 15.4
Here is possible approach using one Image (for demo some small modifications made to use default images). The important changes marked with comments.
enum ImageEnum: String {
case img1 = "1.circle"
case img2 = "2.circle"
case img3 = "3.circle"
func next() -> ImageEnum {
switch self {
case .img1: return .img2
case .img2: return .img3
case .img3: return .img1
}
}
}
struct QuickTest: View {
#State private var img = ImageEnum.img1
#State private var fadeOut = false
var body: some View {
Image(systemName: img.rawValue).resizable().frame(width: 300, height: 300)
.opacity(fadeOut ? 0 : 1)
.animation(.easeInOut(duration: 0.25), value: fadeOut) // animatable fade in/out
.onTapGesture {
self.fadeOut.toggle() // 1) fade out
// delayed appear
DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
withAnimation {
self.img = self.img.next() // 2) change image
self.fadeOut.toggle() // 3) fade in
}
}
}
}
}
I haven't tested this code, but something like this might be a bit simpler:
struct ContentView: View {
#State private var img = ImageEnum.img1
var body: some View {
Image(img.rawValue)
.id(img.rawValue)
.transition(.opacity.animation(.default))
.onTapGesture {
withAnimation {
self.img = self.img.next()
}
}
}
}
The idea is tell SwiftUI to redraw the Image whenever the filename of the asset changes by binding the View's identity to the filename itself. When the filename changes, SwiftUI assumes the View changed and a new View must be added to the view hierarchy, thus the transition is triggered.

Resources