Everything works as expected until I add the paging behavior to the scrollView with a non-zero content margin. The paging behavior ends up not being centered on the cards.
Here is a simple example:
import SwiftUI
struct CarouselView: View {
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 0) {
ForEach(0 ..< 5, id: \.self) { _ in
RoundedRectangle(cornerRadius: 25)
.fill(.ultraThinMaterial)
.containerRelativeFrame(.horizontal)
.scrollTransition(axis: .horizontal, transition: {
content, phase in
content
.scaleEffect(x: phase.isIdentity ? 1 : 0.8, y: phase.isIdentity ? 1 : 0.8)
})
}
}
.scrollTargetLayout()
}
.scrollTargetBehavior(.paging)
.contentMargins(60) // NOTE: I want to see the sides of the next and previous card
.background(Gradient(colors: [.purple, .red]))
}
}
Thanks!
Post not yet marked as solved
Hi,
I'm developing an app using SwiftUI for both iOS and Mac OS and use onOpenURL to handle external links. However, this doesn't seem to work after switching to a single window app on Mac OS.
This code works:
WindowGroup {
Text("Hi").onOpenURL { url in
print("Open URL", url)
}
}
But this doesn't:
Window("My App", id: "my_app") {
Text("Hi").onOpenURL { url in
print("Open URL", url)
}
}
Anyone knows a workaround? Thanks!
Post not yet marked as solved
I need to create a carousel component with the following requirements (sorted by relevance):
Objectives
Every image is 16:9 aspect ratio and resizes to fit the screen.
Needs a zoom and pan functionality, possibly the same way as iOS Photos app.
Needs to work both in landscape and portrait mode, with a smooth transition between orientations.
When orientation changes, the image needs to be rotated to preserve the center of the image (like Photos app and hyperoslo/Lightbox)
The component should only take the minimum necessary space. In most use cases, such component should have other subviews both above and below.
Circularity. I would like the carousel to wrap around.
What I tried:
Using a TabView with .tabViewStyle(PageTabViewStyle()).indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always)) modifiers.
This didn't work: rotating the interface caused the view to get stuck between pages (it looks like it's a well known [bug]).(https://stackoverflow.com/questions/72435939/swiftui-tabview-is-not-working-properly-on-orientation-change).
Implementing a single page (that is, an image view) using an UIScrollView and an UIViewRepresentable, then collecting them into an HStack.
Unfortunately I need to use zoomScale and contentOffset properties of the UIScrollView outside of the UIViewRepresentable itself. The net result was that .init() was invoked for every image in the carousel at every rotation, causing severe stutters and an horrible rotation animation.
Implementing the whole carousel using UIKit, and an UICollectionView, whose cells were an instance of UIScrollView.
The problem is, the UIScrollView needs to recompute its constraints upon rotation but a cell is an instance of UIView, so it can't respond to rotations via viewWillTransition(to:CGSize, with: any UIViewControllerTransitionCoordinator).
In the UICollectionView itself, you can only access the visible cells (one at a time is visible), and cells are cached, so even after rotating, some occasionally are presented on screen with the same appearance as before the rotation (some do, some don't, in the same UICollectionView). Also when rotating, it looks like the UIScrollView of the visible cell is being recreated, making it impossible to preserve the image center (I use this subclass of UIScrollView for this purpose). And the UICollectionView is taking the full window size, not just the bare minimum necessary space.
Help:
With all of this in mind, what options do I realistically have? If necessary I can raise the minimum iOS version to 16.0, even though I guess it doesn't make any significative difference since SwiftUI introduced MagnifyGesture only from iOS 17.0.
Post not yet marked as solved
I am trying to add capabilities in my Vision OS application but ending up in failure it doesn't add any with out any error or notifications is Apple disabled this feature or potentially a BUG
Post not yet marked as solved
Using a NavigationStack and manipulating the NavigationPath “too fast” compared to the animation of the screen can leed visual artifacts and invalid state.
For example, let's create simple stack and create a custom back button.
struct StepView: View {
let value: Int
let action: () -> Void
var body: some View {
VStack {
Text("\(value)")
Button("Next", action: action)
}
}
}
struct ContentView: View {
@State var navigationPath: [Int] = []
var body: some View {
VStack {
if !self.navigationPath.isEmpty {
Button("Back customg") {
self.navigationPath.removeLast()
}
}
Divider()
NavigationStack(path: self.$navigationPath) {
Text("Root")
Button("Next") {
self.navigationPath.append(1)
}
.navigationDestination(for: Int.self) { integer in
StepView(value: integer) {
self.navigationPath.append(integer + 1)
}.navigationBarBackButtonHidden()
}
}
}
.padding()
}
}
Clicking fast on the custom back button will displays some blank screens and may leed to a crash.
Is something missing the API usage ? 🤔
Post not yet marked as solved
I want to add this button with some space in a tab bar I don't know what this button is called and how to add it in Vision Pro app
Post not yet marked as solved
Please take a look at the following simple SwiftUI View:
struct ContentView: View {
var body: some View {
ForEach(1...1, id: \.self) { i in
subview(i)
}
}
func subview(_ i: Int) -> some View
{
print("creating subview \(i)")
return Text("Hello, world!")
}
}
When this View is displayed, all subviews are created twice, as the print statements show. (Unfortunately the Apple Developer Forums UI does not let me attach my sample Xcode project.) This happens on macOS 14.4.1.
Am I doing something wrong or is this a SwiftUI bug? (In a real-world application the View creation can be expensive…)
Post not yet marked as solved
I have view hierarchy like this:
NavigationView {
VStack {
ScrollView {
// some content
}
.background(NavigationLink(destination:
MyView(),
isActive: $isActive) {
EmptyView()
})
// snipped
}
}
When the user follows the navigation link to MyView, by default NavigationBar and MyView is laid out like in a VStack. How can I make them like in a ZStack(alignment: .topLeading) ? i.e. I like MyView extends beneath the NavigationBar.
Here is the MyView:
GeometryReader { geo in
HStack {
// some content
}
.onAppear {
hideNavigationbar = false
}
.onTapGesture(perform: {
hideNavigationbar.toggle()
})
.navigationBarHidden(hideNavigationbar)
.navigationBarTitleDisplayMode(.inline)
// snipped
}
The problem is, when hideNavigationbar toggles, MyView would shift up and down because its height would change. I want NavigationBar sits on top of MyView like in a ZStack so that when NavigationBar hides, MyView will not shift (only uncover its top portion).
What is the proper way to achieve that?
XCode: 15.3 using SwiftUI
iOS: 15
Post not yet marked as solved
Hi,
I am running into an error on XCode 15 (iOS 17+). When I am trying to play an iframe on the app. I see this error popup.
Warning: -[BETextInput attributedMarkedText] is unimplemented
Failed to request allowed query parameters from WebPrivacy.
How do I fix this issue? I never saw this before so I am sure it is new. The app use to run fine as well.
I have a two-view app where the main view is a procedural animation and a secondary view controls settings for the animation. I want to use Play/Pause to toggle between the views, but can't figure out how to do this.
Ideally the main view does not have any visible control and the whole screen can be dedicated to the animation view. Attaching onPlayPauseCommand to the main view does not work. I've also tried managing focus using onFocus without success.
I'm open to other ways to toggle between the main and settings views, it's just that Play/Pause seems the most intuitive.
I am developing an app in mixed immersive native app on Vision Pro. In my RealityView, I add my scene by content.add(mainGameScene). Normally the anchored position (original coord) should be the device position but on the ground (with y == 0 on the ground). At least this is how I understand the RealityViewContent works. So if I place something at position (0, 0, -1.0), the object should be in the front of you but on the floor (z axis is pointing backwards)
However recently I load a different scene and I add that with same code, content.add(mainGameScene), something has changed, my scene randomly anchored on the floor or ceiling, according to the places I stand or sit. When I open Visualizations of my anchoring point, I could see that anchor point I am using is on the ceiling. The correct one (around my foots) is left over there.
How could I switch to the correct anchored position? Or does any setting can change the behavior of default RealityViewContent?
Post not yet marked as solved
I've found a strange leak, that looks like a bug.
When we open two sheets, or fullscreenCovers and the last one has a TextField, then after closing both, @StateObject property is not released.
If you delete TextField, there will be no memory leak.
It works well and memory is releasing on iOS 16 built with Xcode 15 (simulators)
Memory is leaking and not releasing on iOS 17 built with Xcode 15 (simulators, device 17.4.1)
import SwiftUI
struct ContentView: View {
@State var isFirstOpen: Bool = false
var body: some View {
Button("Open first") {
isFirstOpen = true
}
.sheet(isPresented: $isFirstOpen) {
FirstView()
}
}
}
struct FirstView: View {
@StateObject var viewModel = LeakedViewModel()
var body: some View {
ZStack {
Button("Open second") {
viewModel.isSecondOpen = true
}
}
.sheet(isPresented: $viewModel.isSecondOpen) {
SecondView(onClose: {
viewModel.isSecondOpen = false
})
}
}
}
final class LeakedViewModel: ObservableObject {
@Published var isSecondOpen: Bool = false
init() { print("LeakedViewModel init") }
deinit { print("LeakedViewModel deinit") }
}
struct SecondView: View {
@State private var text: String = ""
private let onClose: () -> Void
init(onClose: @escaping () -> Void) {
self.onClose = onClose
}
var body: some View {
Button("Close second"){
onClose()
}
TextField("text: $text", text: $text)
// Comment TextField and the leak will disappear, viewModel deinit called
}
}
@main
struct LeaksApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
May be related to https://forums.developer.apple.com/forums/thread/738840
WatchOS accessoryInline类型的表盘组件不展示自定义的png图片
Post not yet marked as solved
Hi all apple devs! I am a young developer who is completely new to everything programming. I am currently trying to develop an app where I want to use visionkit, but I can't for the life of me figure out how to implement its features. I've been stuck on this for several days, so I am now resorting to asking all of you experts for help! Your assistance would be immensely appreciated!
I started to develop the app trying to exclusively use swiftUI to futureproof my app. Upon figuring out what visionkit is, to my understanding it is more compatible with UIkit? So I rewrote the part of my code that will use visionkit into a UIkit based view, to simplify the integration of visionkits features. It might just have overcomplicated my code? Can visionkit be easily implemented using only swiftUI? I noticed in the demo on the video tutorial the code is in a viewcontroller not a contentview, is this what makes my image unresponsive?
My image is not interactable like her demo in the video, where in my code do I go wrong? Help a noob out!
The desired user flow is like this: User selects an image through the "Open camera" or "Open Camera Roll" buttons. Upon selection the UIkit based view opens and the selected image is displayed on it. (This is where I want to implement visionkit features) User interacts with the image by touching on it, if touching on a subject, the subject should be lifted out of the rest of the image and be assigned to the editedImage, which in turn displays only the subject without the background on the contentview. (For now the image is assigned to editedimage by longpressing without any subjectlifting since I cant get visionkit to work as I want)
Anyways, here's a code snippet of my peculiar effort to implement subject lifting and visionkit into my app:
Post not yet marked as solved
hi
I have been using WKWebView embedded in a UIViewRepresentable for displaying inside a SwiftUI View hierarchy, but when I try the same code on 17,5 beta (simulator) the code fails.
In fact, the code runs (no exceptions raised or anything) but the web view does not render. In the console logs I see:
Warning: -[BETextInput attributedMarkedText] is unimplemented
Error launching process, description 'The operation couldn’t be completed. (OSStatus error -10814.)', reason ''
The code I am using to present the view is:
struct MyWebView: UIViewRepresentable {
let content: String
func makeUIView(context: Context) -> WKWebView {
// Javascript that disables pinch-to-zoom by inserting the HTML viewport meta tag into <head>
let source: String = """
var meta = document.createElement('meta');
meta.name = 'viewport';
meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no';
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '*:focus{outline:none}body{margin:0;padding:0}';
var head = document.getElementsByTagName('head')[0];
head.appendChild(meta);
head.appendChild(style);
"""
let script: WKUserScript = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
let userContentController: WKUserContentController = WKUserContentController()
let conf = WKWebViewConfiguration()
conf.userContentController = userContentController
userContentController.addUserScript(script)
let webView = WKWebView(frame: CGRect.zero /*CGRect(x: 0, y: 0, width: 1000, height: 1000)*/, configuration: conf)
webView.isOpaque = false
webView.backgroundColor = UIColor.clear
webView.scrollView.backgroundColor = UIColor.clear
webView.scrollView.isScrollEnabled = false
webView.scrollView.isMultipleTouchEnabled = false
if #available(iOS 16.4, *) {
webView.isInspectable = true
}
return webView
}
func updateUIView(_ webView: WKWebView, context: Context) {
webView.loadHTMLString(content, baseURL: nil)
}
}
This has been working for ages and ages (back to at least ios 15) - something changed. Maybe it is just a problem with the beta 17.5 release?
Post not yet marked as solved
My goal is to create Apples activity ring sparkle effect. So I found Paul Hudson's Vortex library. There is already a spark effect, but I don't know how to create a custom one that fits my needs. I'm still quite new to SwiftUI animations. Does someone have an idea how to do it?
VortexView(createSparkle()) {
Circle()
.fill(.white)
.frame(width: 16)
.tag("circle")
}
func createSparkle() -> VortexSystem {
let system = VortexSystem(tags: ["circle"])
system.birthRate = 150
system.emissionDuration = 0.2
system.idleDuration = 0.5
system.lifespan = 1.5
system.speed = 1.5
system.speedVariation = 0.2
system.angle = .degrees(330)
system.angleRange = .degrees(30)
system.acceleration = [0, 3]
system.dampingFactor = 4
system.colors = .ramp(.white, .yellow, .yellow.opacity(0))
system.size = 0.1
system.sizeVariation = 0.1
system.stretchFactor = 8
return system
}
Vortex project: https://github.com/twostraws/Vortex
Post not yet marked as solved
I have a peculiar situation, where the first time I present a sheet from a Section that has the header: set, the sheet disappears by itself the first time it is presented.
@State private var show = false
// …
List {
Section {
Text("foo")
} header: {
Text("bar")
}
.sheet(isPresented: $show) {
Text("baz")
}
// just to enable
Button("toggle") {
show = true
}
}
In Xcode I get this warning when I present the sheet (taken from our live app):
Attempt to present <_TtGC7SwiftUI29PresentationHostingControllerVS_7AnyView_: 0x10a819e00> on <_TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVS_7AnyViewVS_12RootModifier__: 0x10a020600> (from <_TtGC7SwiftUI32NavigationStackHostingControllerVS_7AnyView_: 0x10a0cba00>) while a presentation is in progress.
Tested on iOS 17.4.1, iPadOS 17.4.0 (Simulator), Xcode 15.3 Previews.
Circumstances
The circumstances are as following: a Section has to be in a List, and have content:, and header: or footer: set to something, and have the .sheet(…) set on the section itself.
The problem does not occur with these sections:
Section {
Text("…")
}
Section {
} footer: {
Text("…")
}
Section {
Text("…")
} header: {
}
… but the following views have the sheet disappear the first time it is presented:
Section {
Text("…")
} header: {
Text("…")
}
Section {
Text("…")
} footer: {
Text("…")
}
Section {
Text("…")
} header: {
Text("…")
} footer: {
Text("…")
}
Is this a known issue, and are there any known workarounds to present from a Section?
My best guess is to move the .sheet(…) to the parent container, but I'll have to restructure part of my code quite a bit to do so 😕
Post not yet marked as solved
My ".navigationTitle" is on my physical iPhone 14 and Simulator iPhone 15 not displayed, on Xcode Preview Screen is it displayed perfect. Why is it and what can i do that is displayed on my iPhone 14.
Post not yet marked as solved
SwiftUI's PhotoPicker doesn't fit into the screen when I place it on a popover and click on it to select a photo.
The relevant code I use:
.popover(
isPresented: $showAttachments
) {
VStack(alignment: .leading, spacing: 20) {
// ...
PhotosPicker(selection: $photos) {
HStack {
Image(systemName: "photo")
Text("Media")
}
}
}
}
It seems like the photo picker is positioned relative to the popover position and I can't find any configuration options regarding to its' positioning.
How to position the PhotoPicker correctly?
Post not yet marked as solved
I'm using NavigationLink(value:label:) and .navigationDestination(for:destination:) in my SwiftUI watchOS app.
However navigating in the app causes the system to emit the following errors to the console:
<NavigationHostingControllerCache>: MISS at depth 1 in free stack
[NavigationHostingControllerCache_UIKit] <_TtGC7SwiftUI32NavigationStackHostingControllerVS_7AnyView_: 0x125015000> containment skipped because sourceNavigationController or destination were nil or sourceNavigationController was equal to destination
[NavigationHostingControllerCache_UIKit] Eject called for index: depth 1 in free stack
Library: SwiftUI, Subsystem: com.apple.SwiftUI , Category: Invalid Configuration
The navigation itself does work fine.
I'm wondering there's something I can do to fix it or if this is an internal issue of the SwiftUI framework and cannot be addressed by me? (i.e. I can ignore this)