I must be missing something here. I want to put a landscape image in a geometry reader that contains a ZStack that contains an image and an overlay centred on top of the Image.
I would like the ZStack and GeoReader's sizes to be the size of Image. (ie I want geometry.size to be the size of the image, which can be used to control the offset of the overlay's position.)
Unfortunately the ZStack also includes the space above the image (ie the top safeArea) and the GeometryReader also includes all the space below the Image. (so geometry.size.height is greater than the height of Image)
I've gone down rabbit holes of adding other items above/below, but I don't seem to be able to prevent the GeometryReader from being vertically greedy.
eg the Text(" ") above the ZStack in the VStack solves the ZStack claiming the top safe area. But adding Text(" ") below the ZStack does not prevent the GeometryReader from claiming more vertical space below the image.
Any/all guidance greatly appreciated.
struct ContentView: View {
var body: some View {
VStack {
// Text(" ")
GeometryReader { geometry in
ZStack {
Image(
uiImage: .init(imageLiteralResourceName: "LandscapeSample")
)
.resizable()
.aspectRatio(contentMode: .fit)
Text("Hello, world!")
.background(.white)
}
.background(.red)
}
.background(.blue)
// Text(" ")
}
}
}
Explore the various UI frameworks available for building app interfaces. Discuss the use cases for different frameworks, share best practices, and get help with specific framework-related questions.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
We have a sample code that initialises an NSAttributed string with simple HTML code and the result differs massively since XCode 16 and iPadOS 18 SDK.
DESCRIPTION OF PROBLEM Since Xcode Version 16.1 HTML content passed into an NSAttributedString is not rendered correctly. Specifically, enumeration characters (such as bullet points or numbers) and the proper indentation for text within list items are missing. As a result, the structure of the HTML content, especially ordered and unordered lists, is not displayed as expected.
STEPS TO REPRODUCE A UILabel was added to the view in a new Objective-C project in Xcode.
A HTML string containing and Tags was converted into an NSAttributedString (With NSAttributedString::initWithData and NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType Parameter)within the viewDidLoad method and assigned to the UILabel.
Expected Result:
The lists should be displayed correctly with enumeration characters and appropriate indentation, as shown in the attached screenshot expected_result.jpeg.
Same Code still works as expected using XCode 15.x
Actual Result:
The list is displayed without enumeration characters or indentation, which matches the attached screenshot actual_result.jpeg.
Sample Code
NSString *html = @"Es ist wichtig, dass Sie Ihren Arzt informieren:\n<ol>\n\t<li><strong>HIER !!!!!!! </strong>Wenn Sie gegenwärtig mit Zometa®, dass die gleiche aktive Substanz enthält wie Aclasta® behandelt werden.</li>\n</ol>\n\n<ul>\n\t<li><strong>Hier !!!!!!</strong> Wenn Sie Nierenbeschwerden haben oder hatten, denn Ihre Nieren müssen korrekt funktionieren, um das überflüssige Aclasta ® das für Ihre Knochen nicht benötigt wird, ausscheiden zu können.</li>\n\t<li>Wenn sie Medikamente einnehmen, die Kortsion als Bestandteil enthalten (z. B. Prendisolon oder Dexamethason)</li>\n\t<li>Wenn sie unter schlechter Zahngesundheit oder Zahnfleischerkrankungen leiden oder wenn eine Zahnextraktion geplant ist</li>\n</ul>\n";
NSString *textAttr = [NSString stringWithFormat:@"<span style=\"font-family:Arial; line-height: 80%%; font-size:10px;\">%@</style>", html];
NSData *data = [textAttr dataUsingEncoding:NSUTF16StringEncoding];
NSAttributedString *string = [[NSAttributedString alloc] initWithData:data
options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: @(NSUTF16StringEncoding)}
documentAttributes:nil error:nil];
self.label.numberOfLines = 0;
self.label.attributedText = string;
Greetings
Hello,
I’m encountering the error "Publishing changes from within view updates is not allowed, this will cause undefined behavior". while developing an app using SwiftUI and ARKit.
I have a ObjectTracking class where I update some @Published variables inside a function called processObjectAttributes after detecting objects. However, when I try to update these state variables in the View (like isPositionChecked, etc.), the error keeps appearing.
Here is a simplified version of my code:
class ObjectTracking: ObservableObject {
@Published var isPositionChecked: Bool = false
@Published var isSizeChecked: Bool = false
@Published var isOrientationChecked: Bool = false
func checkAttributes(objectAnchor: ARObjectAnchor,
_ left: ARObjectAnchor.AttributeLocation,
_ right: ARObjectAnchor.AttributeLocation? = nil,
threshold: Float) -> Bool {
let attributes = objectAnchor.attributes
guard let leftValue = attributes[left]?.floatValue else { return false }
let rightValue = right != nil ? attributes[right!]?.floatValue ?? 0 : 0
return leftValue > threshold && (right == nil || rightValue > threshold)
}
func isComplete(objectAnchor: ARObjectAnchor) -> Bool {
isPositionChecked = checkAttributes(objectAnchor: objectAnchor, .positionLeft, .positionRight, threshold: 0.5)
isSizeChecked = checkAttributes(objectAnchor: objectAnchor, .sizeLeft, .sizeRight, threshold: 0.3)
isOrientationChecked = checkAttributes(objectAnchor: objectAnchor, .orientationLeft, .orientationRight, threshold: 0.3)
return isPositionChecked && isSizeChecked && isOrientationChecked
}
func processObjectAttributes(objectAnchor: ARObjectAnchor) {
currentObjectAnchor = objectAnchor
}
}
In my View, I am using @ObservedObject to observe the state of these variables, but the error persists when I try to update them during view rendering.
Could anyone help me understand why this error occurs and how to avoid it? I understand that state should not be updated during view rendering, but I can’t find a solution that works in this case.
Thank you in advance for your help!
I set the isHidden property of a view in traitCollectionDidChange and found that sometime it does not take effect after being set(value of isHidden actually not changed either). It looks like the setting does not take effect when triggered an even number of times, but it is normal when triggered an odd number of times.
When setting isHidden, what actually goes into is [UIView (Rendering) setHidden:], which internally calls [UIView _ bitFlagValueAfterIncrementingHiddenManagement CountForKey: withIncrement: bitFlagValue:] to handle the relevant logic of "_UIViewPendingHiddenCount". Is this issue related to this part of the processing? returning 0 after calling seems normal
This view is a UIStackView, and it is uncertain whether it is related to the type of view
I'm pretty new to Swift and SwiftUI. I'm making my first app for sorting a gallery with some extra features.
I was using my own iPhone for testing and just started testing my app on other Apple products.
Everything works fine on iPad Air M1, iPhone 15 Pro, iPhone 15 Pro Max, iPhone 13, iPhone XS (Simulator), and iPhone 11 Pro (Simulator). However, when I tried to show my app to a family member with an iPhone 11, I came across an issue.
Issue Description:
My app takes all photos from iPhone's native gallery, then you can sort it by some spesific filters and delete pictures. It just looks like the native gallery. (I can add photos later if needed) You can just scroll the gallery by swiping up and down. You can press the select button and start selecting pictures to delete.
I recently added a drag-to-select-multiple-pictures feature. This makes it feel more like the native iOS experience, eliminating the need to tap each picture individually.
However, on the iPhone 11, the moment you open the app, you can't scroll. Scrolling is completely locked. You can still select pictures by tapping or dragging, so it's not a touch area issue. The same issue persists on the iPhone 11 simulator.
And I think I found the problematic part in my (sadly messy) ContentView.swift file;
ScrollView {
RefreshControl(coordinateSpace: .named("refresh")) {
await viewModel.refreshMediaItems()
}
LazyVGrid(columns: gridColumns, spacing: UIDevice.current.userInterfaceIdiom == .pad ? 12 : 4) {
let items = viewModel.filteredItems(typeFilter: mediaTypeFilter, specialFilter: specialFilter)
ForEach(Array(zip(items.indices, items)), id: \.1.id) { index, item in
MediaThumbnailView(
item: item,
isSelected: selectedItems.contains(item.id),
viewModel: viewModel,
onLongPress: {
if !isSelectionMode {
toggleSelectionMode()
selectedItems.insert(item.id)
}
},
onTap: {
if isSelectionMode {
toggleSelection(item: item)
} else {
viewModel.selectItem(item)
}
}
)
.aspectRatio(1, contentMode: .fit)
.background(
GeometryReader { geometry in
let frame = geometry.frame(in: .named("grid"))
Color.clear.preference(
key: ItemBoundsPreferenceKey.self,
value: [ItemBounds(id: item.id, bounds: frame, index: index)]
)
}
)
}
}
.padding(.horizontal, 2)
.coordinateSpace(name: "grid")
.onPreferenceChange(ItemBoundsPreferenceKey.self) { bounds in
itemBounds = Dictionary(uniqueKeysWithValues: bounds.map { ($0.id, $0) })
itemIndices = Dictionary(uniqueKeysWithValues: bounds.map { ($0.id, $0.index) })
}
.gesture(
DragGesture(minimumDistance: 0)
.onChanged { gesture in
if isSelectionMode {
let location = gesture.location
if !isDragging {
startDragging(at: location, in: itemBounds)
}
updateSelection(at: location, in: itemBounds)
}
}
.onEnded { _ in
endDragging()
}
)
}
.coordinateSpace(name: "refresh")
}
you can see the .gesture(.... part. I realised that this DragGesture and ScrollView blocks each other (somehow only on iPhone 11)
highPriorityGesture also won't work.
When I change it with simultaneousGesture, scroll starts to work again.
BUT - since it's simultaneous, when multiple selection mode is activated, when I'm dragging my finger gallery also starts to scroll and it becomes a very unpleasant experience. After this issue I realised on native gallery iOS locks scroll when you are dragging for multiple selection and just when you release your finger you can scroll again even if the multiple selection mode is active.
I tried a million things, asked claude, chatgpt etc. etc.
Found some similar issues on stackoverflow but they were all related to iOS 18, not spesific to an iPhone. My app works fine on iOS 18 (15 Pro Max)
iOS 18 drag gesture blocks scrollview
Here are the some of the things I've tried: using highPriorityGesture and simultenousgesture together, tried to lock the scroll briefly while dragging, implement much complicated versions of these things with the help of claude, try to check if isSelectionMode is true or not
All of them broke other things/won't work.
Probably there's something pretty simple that I'm just missing; but iPhone 11 being the single problematic device confuses me. I don't want to mess too much with my already fragile logic.
Hi everyone,
I’m working on an iOS app using both UITableViewDiffableDataSource and SwiftUI, and I’m facing two separate but puzzling issues:
UITableViewDiffableDataSource Not Reusing Cells on first applying after initial Snapshot. After applying first time it is working as expected from second time.
SwiftUI View’s inside UITableViewCell onDisappear Not Triggering the on first changes of snapshot after initial snapshot.
With normal UITableView it is working fine.
Issue causing - it is causing player & cells to retain memory extensively
Sample gist code for reproducing with diffable (DiffableTableViewExampleViewController) and working fine without diffable (RegularTableViewExampleViewController)
https://gist.github.com/SURYAKANTSHARMA/d83fa9e7e0de309e27485100ba5aed17
Any insights or suggestions for these issues would be greatly appreciated!
Thanks in advance!
I am trying to give bottom padding to tabbar i.e ** tabBarFrame.origin.y = view.frame.height - tabBarHeight - 30** but it is not moving up from bottom, it gets sticked to bottom = 0 and the tabbar content moving up taher than tabbar itself..
Code snippet is -
`i override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let tabBarHeight: CGFloat = 70 // Custom height for the capsule tab bar
var tabBarFrame = tabBar.frame
tabBarFrame.size.height = tabBarHeight
tabBarFrame.size.width = view.frame.width - 40
tabBarFrame.origin.y = view.frame.height - tabBarHeight - 30
tabBarFrame.origin.x = 20
tabBar.frame = tabBarFrame
tabBar.layer.cornerRadius = tabBarHeight / 2
tabBar.clipsToBounds = true
view.bringSubviewToFront(tabBar)
}`
Can anyone please help to resolve the issue for iOS 18, it is coming in iOS 18 rest previous versions are fine with the code.
As a starter for iOS programming, I want to get the touch’ x-y position on a SwiftUI view , what is the fastest way/api or the highest refresh rate to get the position . UItouch in UIkit ?or other api?
Topic:
UI Frameworks
SubTopic:
General
I'm developing a grid of focusable elements in SwiftUI with different sizes for tvOS (similar to a tv channel grid).
Because the Focus Engine calculates the next view to focus based on the center of the currently focused view, sometimes it changes focus to an unexpected view. Here's an example:
Actual:
Expected:
Is it possible to customize the anchor point from which the focus engine traces a ray to the next view? I would prefer the leading edge in my case.
I would like to be able to write something like:
struct FooView: View
{
let foo: Foo;
var body: some View {
assert(foo.valid);
......
}
};
but of course I can't, because "Type () cannot conform to View".
What's the best way to achieve this?
I have a view that lets the user position and size a bunch of subviews. I use .frame() and .position() to accomplish this.
Right now, if the user resizes the window, the views stay where they are, anchored to the top-left corner. What I'd like is for the views to scale as a whole with window, maintaining their relative position, and their aspect ratios.
I can apply .scaleEffect(_:anchor:) to the containing view, and it scales them the way I want, but I'm not sure how to tie it to the window.
My first thought is to use a GeometryReader, but I don't really know what the "original" size would have been in order to compute a scale factor.
How else might I accomplish this?
Topic:
UI Frameworks
SubTopic:
SwiftUI
struct DeployAndWithdrawDefensesAppIntent: WidgetConfigurationIntent {
// An example configurable parameter.
@Parameter(title:LocalizedStringResource("ax_alarm_device_name"))
}
In the process of using iOS widgetKit development team a, configuration item title need language internationalization (@ Parameter (title: LocalizedStringResource (" ax_alarm_device_name "))),
but found no effect. I first changed the language of the system on the iphone and found that the widget worked. However, just changing the language of the app did not take effect. Is there any way to just change the app language and make the widgets change? Thank you very much!
I want to make my buttons inline with each other, but spaced apart, a bit like the apple topbar BUT in swift.
My code:
struct NormalPageView: View {
var body: some View {
VStack {
NavigationView {
Form {
Section {
Image(systemName: "house.fill")
Spacer()
Image(systemName: "plus")
Spacer()
Image(systemName: "gearshape.fill")
}
}
}
For whatever reason SwiftUI sheets don't seem to be resizable anymore.
The exact same code/project produces resizable Sheets in XCode 15.4 but unresizable ones with Swift included in Xcode 16 beta 2.
Tried explicitly providing .fixedSize(horizontal false, vertical: false) everywhere humanly possible hoping for a fix but sheets are still stuck at an awkward size (turns out be the minWidth/minHeight if I provide in .frame).
This crash occurs when the app is started, and it is not necessary. The probability of occurrence is relatively low and it is not easy to reproduce. Please guide me how to deal with it. Thank you
Please see the crash log below
Crash log
Making the call as:
UIApplication.shared.open(websiteURL)
doesn't open the browser and gives the following in the console:
BUG IN CLIENT OF UIKIT: The caller of UIApplication.openURL(:) needs to migrate to the non-deprecated UIApplication.open(:options:completionHandler:). Force returning false (NO).
However, making the call as:
UIApplication.shared.open(websiteURL) { _ in }
opens the browser and there is nothing in the cosole.
Does someone understand why is this or if it's Apple's iOS 18 bug? In the iOS & iPadOS 18 RC Release Notes | Apple Developer Documentation there is a section around resolving this or something similar, unsure.
Topic:
UI Frameworks
SubTopic:
UIKit
SwiftUI Buttons in a List no longer highlight when tapped. Seems to have stopped highlighting after iOS 16.0 I've only tested on an iPhone/simulators so not sure if iPad has the same issue.
The issue has been carried over to iOS 17 Beta 4. My app does not feel Apple like as there is no visual feedback for the user when a button in the list is pressed.
Does anyone know why this is occurring? Is this a bug on Apple's end?
I have a simple SwiftUI Text:
Text(t) .font(Font.system(size: 9))
Strangely its ideal height seems to be larger when it is empty.
I initially observed this in a custom Layout container that wasn't working quite right. Eventually I looked at the height returned by v.dimensions(in:), and found that when t is non-empty the height is 11; when empty, it's 14.
Subsequently I observed similar behaviour in a regular VStack container.
Has anyone seen anything similar? Are there any properties that could affect this behaviour?
(This is on a watch - I don't know if that matters.)
Hi,
Despite having CarPlay capabilities authorised for our navigation app, our users are seeing some odd behaviour in the appearance of the icon in the sidebar menu on the side of the CarPlay display.
The documentation suggests the quickbar will show the most recently used: navigation app,
Open our app in CarPlay
Switch to another non-navigation app via CarPlay sidebar
Note that our navigation app remains in sidebar
Switch back to our navigation app
Search for destination, select, tap 'Let's Go' to start navigation
Switch to a non-navigation app via CarPlay sidebar
Note that our app is replaced by another navigation app in the sidebar (Google/Apple), despite being the most recently used
Any ideas?
Not sure what could cause this. the UI align differently running on iPhone versus running on Mac. If I remove the HStack, it works but I still would like to know why, and if there is a way to make it right on both platforms.
Thank you
here is my code
@State private var viewModel = FirmwareSelectionViewModel()
var body: some View {
Form {
Section("Setup Name") {
TextField ( "", text: $viewModel.setupName )
.foregroundColor(.green )
.disableAutocorrection(true)
.onSubmit {
print ("On Submit")
}
}
Section("Battery") {
HStack() {
Text("Volt")
TextField("", value: $viewModel.Vnominal, format: .number)
.textFieldStyle(.roundedBorder)
.foregroundColor(.green )
#if !os(macOS)
.keyboardType(.decimalPad)
#endif
.onChange(of: viewModel.Vnominal) {
viewModel.checkEntryValidity()
print("Updated Vnominal: \(viewModel.Vnominal)")
}
Text("Ah")
TextField("", value: $viewModel.batteryCapacity, format: .number)
.textFieldStyle(.roundedBorder)
.foregroundColor(.green )
#if !os(macOS)
.keyboardType(.decimalPad)
#endif
.onChange(of: viewModel.batteryCapacity) {
viewModel.checkEntryValidity()
print("Updated Battery Capacity: \(viewModel.batteryCapacity)")
}
}
}
Section("Firmware Type") {
Picker(selection: $viewModel.selectedType, label: EmptyView()) {
ForEach(TypeOfFirmware.allCases) { type in
Text(type.rawValue).tag(type as TypeOfFirmware)
.foregroundColor(.green )
}
}
.pickerStyle(SegmentedPickerStyle())
Picker(selection: $viewModel.selectedFirmware, label: EmptyView()) {
ForEach(viewModel.availableFirmware) { firmware in
Text(firmware.rawValue.capitalized).tag(firmware as Firmware)
}
}
.pickerStyle(SegmentedPickerStyle())
}
}
.onChange(of: viewModel.selectedType) {
viewModel.resetFirmwareSelection()
}
.navigationTitle("Firmware Selection")
}
}
Topic:
UI Frameworks
SubTopic:
SwiftUI