Goal : Drag a sphere across the room and track it's position
Problem: The gesture seems to have no effect on the sphere ModelEntity. I don't know how to properly attach the gesture to the ModelEntity. Any help is great. Thank you
import SwiftUI
import RealityKit
import RealityKitContent
import Foundation
@main
struct testApp: App {
@State var immersionStyle:ImmersionStyle = .mixed
var body: some Scene {
ImmersiveSpace {
ContentView()
}
.immersionStyle(selection: $immersionStyle, in: .mixed, .full, .progressive)
}
}
struct ContentView: View {
@State private var lastPosition: SIMD3<Float>? = nil
@State var subscription: EventSubscription?
@State private var isDragging: Bool = false
var sphere: ModelEntity {
let mesh = MeshResource.generateSphere(radius: 0.05)
let material = SimpleMaterial(color: .blue, isMetallic: false)
let entity = ModelEntity(mesh: mesh, materials: [material])
entity.generateCollisionShapes(recursive: true)
return entity
}
var drag: some Gesture {
DragGesture()
.targetedToEntity(sphere)
.onChanged { _ in self.isDragging = true }
.onEnded { _ in self.isDragging = false }
}
var body: some View {
Text("Hello, World!")
RealityView { content in
//1. Anchor Entity
let anchor = AnchorEntity(world: SIMD3<Float>(0, 0, -1))
let ball = sphere
//1.2 add component to ball
ball.components.set(InputTargetComponent())
//2. add anchor to sphere
anchor.addChild(ball)
content.add(anchor)
subscription = content.subscribe(to: SceneEvents.Update.self) { event in
let currentPosition = ball.position(relativeTo: nil)
if let last = lastPosition, last != currentPosition {
print("Sphere moved from \(last) to \(currentPosition)")
}
lastPosition = currentPosition
}
}
.gesture(drag)
}
}
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
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 upgrading my app from minVersion iOS 11 to iOS 12. My compiler says that UIDocumentMenuViewController with UIDocumentPickerViewController is deprecated, they recommend to use directly the last one. So I change the code.
fileprivate func openDocumentPicker() {
let documentPicker = UIDocumentPickerViewController(
documentTypes: [
"com.adobe.pdf",
"org.openxmlformats.wordprocessingml.document", // DOCX
"com.microsoft.word.doc" // DOC
],
in: .import
)
documentPicker.delegate = self
view.window?.rootViewController?.present(documentPicker, animated: true, completion: nil)
}
When I open the picker in iOS 17.2 simulator and under it is well shown, like a page sheet. But in iOS 18.0 and up at first it opens like a page sheet with no content but then it is displayed as a transparent window with no content. Is there any issue with this component and iOS 18? If I open the picker through UIDocumentMenuViewControllerDelegate in an iphone with iOS 18.2 it is well shown.
Image in iOS 18.2 with the snippet
The same snippet in iOS 17.2 (and expected in older ones)
I want to record screen ,and than when I call the method stopCaptureWithHandler:(nullable void (^)(NSError *_Nullable error))handler to stop recording and saving file. before call it,I check the value record of RPScreenRecorder sharedRecorder ,the value is false , It's weird! The screen is currently being recorded !
I wonder if the value of [RPScreenRecorder sharedRecorder].record will affect the method stopCaptureWithHandler:
-(void)startCaptureScreen {
[[RPScreenRecorder sharedRecorder] startCaptureWithHandler:^(CMSampleBufferRef _Nonnull sampleBuffer, RPSampleBufferType bufferType, NSError * _Nullable error) {
//code
} completionHandler:^(NSError * _Nullable error) {
//code
}];
}
- (void)stopRecordingHandler {
if([[RPScreenRecorder sharedRecorder] isRecording]){
// deal error .sometime isRecording is false
}else {
[[RPScreenRecorder sharedRecorder] stopCaptureWithHandler:^(NSError * _Nullable error) {
}];
}
}
here are my code.
Hi! I'm seeing some weird animation issues building the Food Truck sample application.^1 I'm running from macOS 15.4 and Xcode 16.3. I'm building the Food Truck application for macOS. I'm not focusing on iOS for now.
The FoodTruckModel adds new Order values with an animation:
// FoodTruckModel.swift
withAnimation(.spring(response: 0.4, dampingFraction: 1)) {
self.orders.append(orderGenerator.generateOrder(number: orders.count + 1, date: .now, generator: &generator))
}
This then animates the OrdersTable when new Order values are added.
Here is a small change to OrdersTable:
// OrdersTable.swift
- @State private var sortOrder = [KeyPathComparator(\Order.status, order: .reverse)]
+ @State private var sortOrder = [KeyPathComparator(\Order.creationDate, order: .reverse)]
Running the app now inserts new Order values at the top.
The problem is I seem to be seeing some weird animation issues here. It seems that as soon as the new Order comes in there is some kind of weird glitch where it appears as if part the animation is coming from the side instead of down from the top:
What's then more weird is that if I seem to affect the state of the Table in any way then the next Order comes in with perfect animation.
Scrolling the Table fixes the animation.
Changing the creationData sort order from reverse to forward and back to reverse fixes the animation.
Any ideas? Is there something about how the Food Truck product is built that would cause this to happen? Is this an underlying issue in the SwiftUI infra?
I recently detected a special crash on 18.0, 18.1, 18.1.1, 18.2,18.3 which cannot be repeated, and the page logs are related to the keyboard, is there any idea to deal with this problem?
Exception Category: nsexception
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x00000000 at 0x0000000000000000
Crashed Thread: 0
CrashDoctor Diagnosis: Application threw exception NSInternalInconsistencyException: Multi layer delegate table missing.
Thread 0 Crashed:
0 CoreFoundation 0x00000001869d87cc __exceptionPreprocess + [ : 164]
1 libobjc.A.dylib 0x0000000183cab2e4 objc_exception_throw + [ : 88]
2 Foundation 0x0000000185da88d8 _userInfoForFileAndLine
3 UIKitCore 0x0000000189e78074 -[UIView _multiLayerDelegatesTableCreateIfNecessary:] + [ : 208]
4 UIKitCore 0x0000000189e780c4 -[UIView _registerMultiLayerDelegate:] + [ : 36]
5 UIKitCore 0x00000001894874c0 -[_UIPortalView setSourceView:] + [ : 132]
6 UIKitCore 0x000000018a1eb6bc -[_UIPortalView initWithSourceView:] + [ : 68]
7 UIKitCore 0x000000018a213ea4 -[_UITextMagnifiedLoupeView initWithSourceView:] + [ : 444]
8 UIKitCore 0x000000018a6c461c +[UITextLoupeSession _makeLoupeViewForSourceView:selectionWidget:orientation:] + [ : 84]
9 UIKitCore 0x000000018a6c47bc +[UITextLoupeSession _beginLoupeSessionAtPoint:fromSelectionWidgetView:inView:orientation:] + [ : 304]
10 UIKitCore 0x0000000189d50ce0 -[UITextRefinementTouchBehavior textLoupeInteraction:gestureChangedWithState:location:translation:velocity:modifierFlags:shouldCancel:] + [ : 1756]
11 UIKit 0x0000000240e309e0 -[UITextRefinementTouchBehaviorAccessibility textLoupeInteraction:gestureChangedWithState:location:translation:velocity:modifierFlags:shouldCancel:] + [ : 216]
12 UIKitCore 0x000000018a4d45b4 -[UITextRefinementInteraction loupeGestureWithState:location:translation:velocity:modifierFlags:shouldCancel:] + [ : 124]
13 UIKitCore 0x000000018a4d3f74 -[UITextRefinementInteraction loupeGesture:] + [ : 548]
14 UIKitCore 0x000000018952eac4 -[UIGestureRecognizerTarget _sendActionWithGestureRecognizer:] + [ : 128]
15 UIKitCore 0x000000018952e934 _UIGestureRecognizerSendTargetActions + [ : 92]
16 UIKitCore 0x000000018952e6f4 _UIGestureRecognizerSendActions + [ : 284]
17 UIKitCore 0x00000001891e1b28 -[UIGestureRecognizer _updateGestureForActiveEvents] + [ : 572]
18 UIKitCore 0x00000001891b3724 _UIGestureEnvironmentUpdate + [ : 2488]
19 CoreFoundation 0x000000018697a1f4 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + [ : 36]
20 CoreFoundation 0x0000000186979f98 __CFRunLoopDoObservers + [ : 552]
21 CoreFoundation 0x00000001869a9028 __CFRunLoopRun + [ : 948]
22 CoreFoundation 0x00000001869a8830 CFRunLoopRunSpecific + [ : 588]
23 GraphicsServices 0x00000001d29881c4 GSEventRunModal + [ : 164]
24 UIKitCore 0x000000018950eeb0 -[UIApplication _run] + [ : 816]
25 UIKitCore 0x00000001895bd5b4 UIApplicationMain + [ : 340]
26 顺丰小哥 0x0000000104423cc0 main + [main.m : 13]
27 (null) 0x00000001ac396ec8 0x0 + 7184412360
Topic:
UI Frameworks
SubTopic:
UIKit
I currently face an Issue where the SafeAreaInsets on the iPhone 16 Pro Max is not respected on LaunchScreens.
Lets say you have an ImageView whose leading, trailing and top are equal to the SafeAreaLayoutGuides leading, trailing and top.
Then you have a SwiftUI View such as the following representing the same layout in code:
GeometryReader { reader in
ZStack {
VStack(spacing: 0) {
Spacer(minLength: 0)
.frame(height: reader.safeAreaInsets.top)
Image(decorative: "splashLogo")
Spacer(minLength: 0)
}
.frame(width: reader.size.width)
}
.edgesIgnoringSafeArea(.all)
}
Both the storyboard preview as well as the SwiftUI preview show identical results in Xcode. Launching the app on the device however briefly shows the image below the Dynamic Island cutout until the app is launched to the SwiftUI view. Noticed this only happening on the iPhone 16 Pro Max.
Topic:
UI Frameworks
SubTopic:
General
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
I am facing same issue with major crash while coming out from this function.
Basically using collectionView.dequeReusableCell with size calculation.
func getSizeOfFavouriteCell(_ collectionView: UICollectionView, at indexPath: IndexPath, item: FindCircleInfoCellItem) -> CGSize { guard let dummyCell = collectionView.dequeueReusableCell( withReuseIdentifier: TAButtonAddCollectionViewCell.reuseIdentifier, for: indexPath) as? TAButtonAddCollectionViewCell else { return CGSize.zero }
dummyCell.title = item.title
dummyCell.subtitle = item.subtitle
dummyCell.icon = item.icon
dummyCell.layoutIfNeeded()
var targetSize = CGSize.zero
if viewModel.favoritesDataSource.isEmpty.not,
viewModel.favoritesDataSource.count > FindSheetViewControllerConstants.minimumFavoritesToDisplayInSection {
targetSize = CGSize(width: collectionView.frame.size.width / 2, height: collectionView.frame.height)
var estimatedSize: CGSize = dummyCell.systemLayoutSizeFitting(targetSize)
if estimatedSize.width > targetSize.width {
estimatedSize.width = targetSize.width
}
return CGSize(width: estimatedSize.width, height: targetSize.height)
}
}
We have resolve issue with size calculation with checking nil. Working fine in xcode 15 and 16+.
Note: Please help me with reason of crash? Is it because of xCode 16.2 onwards **strict check on UICollectionView **
Working on a MacOS SwiftUI app - recently, when the app stays running from the night before, it no longer responds to keystrokes - data entry, or cursor navigation keys.
It does respond to mouse activity and clicks ... very weird.
Hi Apple team and community,
We’re encountering a strange issue with Live Activity that seems related to memory management or background lifecycle.
❓ Issue:
Our app updates a Live Activity regularly (every 3 minutes) using .update(...). However, after the app remains in the background for around 8 hours, the Live Activity reverts to the initial state that was passed into .request(...).
Even though the app continues sending updates in the background, the UI on the Lock Screen and Dynamic Island resets to the original state.
We're encountering a UX challenge with the automatic App Store notification banner that appears when users first launch our App Clips (not the App Clip sheet). This notification, which suggests downloading the full app, is creating confusion among our users. We've observed that some users tap the notification instead of completing their intended action within the App Clip, interrupting their workflow.
Is there a way to disable this banner?
Hi, I'm working on RealityView and I have two entities in RCP. In order to set views for both entities, I have to create two separate attachments for each entity. What I want to achieve is that when I hover (by eye) on one entity's attachment, it would trigger the hover effect of the other entity's attachment. I try to use the hoverEffectGroup, but it would only activate the hover effect in a subview, instead a complete separate view. I refer to the following WWDC instruction for the hover effect.
https://developer.apple.com/videos/play/wwdc2024/10152/
Anyone know how to reduce the padding between list section header (plain style) and search bar? I have tried all available method on google but none work. The default list style does not have this big padding/space between the section header and the search bar.
struct Demo: View {
@State private var searchText: String = ""
var body: some View {
NavigationStack {
List {
Section {
ForEach(0..<100) { index in
Text("Sample value for \(index)")
}
} header: {
Text("Header")
.font(.headline)
}
}
.listStyle(.plain)
.navigationTitle("Demo")
.navigationBarTitleDisplayMode(.inline)
.searchable(text: $searchText)
}
}
}
I have an app which uses Scene
var body: some Scene {
WindowGroup {
RootView(root: appDelegate.root)
.edgesIgnoringSafeArea(.all)
.onOpenURL { url in
let stringUrl = url.absoluteString
if (stringUrl.starts(with: "http")) {
handleUniversalLink(url: stringUrl)
} else if (stringUrl.starts(with: "fb")) {
let _ = ApplicationDelegate.shared.application(
UIApplication.shared,
open: url,
sourceApplication: nil,
annotation: [UIApplication.OpenURLOptionsKey.annotation])
}
}
}
}
I need to detect when a user taps on status bar. And call some functions when he does it. Is it possible in Swift?
Topic:
UI Frameworks
SubTopic:
SwiftUI
private let datePicker = {
let picker = UIDatePicker()
picker.backgroundColor = .clear
picker.datePickerMode = .dateAndTime
picker.preferredDatePickerStyle = .compact
return picker
}()
My assumption has always been that [NSApp runModalForWindow:] runs a modal window in NSModalPanelRunLoopMode.
However, while -[NSApplication _doModalLoop:peek:] seems to use NSModalPanelRunLoopMode when pulling out the next event to process via nextEventMatchingMask:untilDate:inMode:dequeue:, the current runloop doesn't seem to be running in that mode, so during -[NSApplication(NSEventRouting) sendEvent:] of the modal-specific event, NSRunLoop.currentRunLoop.currentMode returns kCFRunLoopDefaultMode.
From what I can tell, this means that any event processing code that e.g. uses [NSTimer addTimer:forMode:] based on the current mode will register a timer that will not fire until the modal session ends.
Is this a bug? Or if not, is the correct way to run a modal session something like this?
[NSRunLoop.currentRunLoop performInModes:@[NSModalPanelRunLoopMode] block:^{
[NSApp runModalForWindow:window];
}];
[NSRunLoop.currentRunLoop limitDateForMode:NSModalPanelRunLoopMode];
Alternatively, if the mode of the runloop should stay the same, I've seen suggestions to run modal sessions like this:
NSModalSession session = [NSApp beginModalSessionForWindow:theWindow];
for (;;) {
if ([NSApp runModalSession:session] != NSModalResponseContinue)
break;
[NSRunLoop.currentRunLoop limitDateForMode:NSModalPanelRunLoopMode];
}
[NSApp endModalSession:session];
Which would work around the fact that the timer/callbacks were scheduled in the "wrong" mode. But running NSModalPanelRunLoopMode during a modal session seems a bit scary. Won't that potentially break the modality?
I have an app that run Monte Carlo simulations. I run thousands of simulations in the app and a simulation runs can take on the order of 30 seconds to a minute to complete. I would like to have a progress view that tracks the number of simulation runs. How can I implement this in swiftui?
I set UIToolbar and UIBarButtonItem to UITextField placed on Xib, but when I run it on iOS18 iPad, the following error is output to Xcode Console, and UIPickerView set to UITextField.inputView is not displayed.
Error: this application, or a library it uses, has passed an invalid numeric value (NaN, or not-a-number) to CoreGraphics API and this value is being ignored. Please fix this problem.
If you want to see the backtrace, please set CG_NUMERICS_SHOW_BACKTRACE environmental variable.
Backtrace:
<CGPathAddLineToPoint+71>
<+[UIBezierPath _continuousRoundedRectBezierPath:withRoundedCorners:cornerRadii:segments:smoothPillShapes:clampCornerRadii:]
<+[UIBezierPath _continuousRoundedRectBezierPath:withRoundedCorners:cornerRadius:segments:]+175>
<+[UIBezierPath _roundedRectBezierPath:withRoundedCorners:cornerRadius:segments:legacyCorners:]+338>
<-[_UITextMagnifiedLoupeView layoutSubviews]+2233>
<__56-[_UITextMagnifiedLoupeView _updateCloseLoupeAnimation:]_block_invoke+89>
<+[UIView(UIViewAnimationWithBlocksPrivate) _modifyAnimationsWithPreferredFrameRateRange:updateReason:animations:]+166>
<block_destroy_helper.269+92>
<block_destroy_helper.269+92>
<__swift_instantiateConcreteTypeFromMangledName+94289>
<block_destroy_helper.269+126>
<+[UIView(UIViewAnimationWithBlocks) _setupAnimationWithDuration:delay:view:options:factory:animations:start:anima
<block_destroy_helper.269+6763>
<block_destroy_helper.269+10907>
<-[_UITextMagnifiedLoupeView _updateCloseLoupeAnimation:]+389>
<-[_UITextMagnifiedLoupeView setVisible:animated:completion:]+256>
<-[UITextLoupeSession _invalidateAnimated:]+329>
<-[UITextRefinementTouchBehavior textLoupeInteraction:gestureChangedWithState:location:translation:velocity:
<-[UITextRefinementInteraction loupeGestureWithState:location:translation:velocity:modifierFlags:shouldCanc
<-[UITextRefinementInteraction loupeGesture:]+701>
<-[UIGestureRecognizerTarget _sendActionWithGestureRecognizer:]+71>
<_UIGestureRecognizerSendTargetActions+100>
<_UIGestureRecognizerSendActions+306>
<-[UIGestureRecognizer _updateGestureForActiveEvents]+704>
<_UIGestureEnvironmentUpdate+3892>
<-[UIGestureEnvironment _updateForEvent:window:]+847>
<-[UIWindow sendEvent:]+4937>
<-[UIApplication sendEvent:]+525>
<__dispatchPreprocessedEventFromEventQueue+1436>
<__processEventQueue+8610>
<updateCycleEntry+151>
<_UIUpdateSequenceRun+55>
<schedulerStepScheduledMainSection+165>
<runloopSourceCallback+68>
<__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__+17>
<__CFRunLoopDoSource0+157>
<__CFRunLoopDoSources0+293>
<__CFRunLoopRun+960>
<CFRunLoopRunSpecific+550>
<GSEventRunModal+137>
<-[UIApplication _run]+875>
<UIApplicationMain+123>
<__debug_main_executable_dylib_entry_point+63>
10d702478 204e57345
Type: Error | Timestamp: 2025-03-09 00:22:46.121407+09:00 | Process: FurusatoLocalCurrency | Library: CoreGraphics | Subsystem: com.apple.coregraphics | Category: Unknown process name | TID: 0x5c360
Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
"<NSAutoresizingMaskLayoutConstraint:0x600002202a30 h=--& v=--& _UIToolbarContentView:0x7fc2c6a5b8f0.width == 0 (active)>",
"<NSLayoutConstraint:0x600002175e00 H:|-(0)-[_UIButtonBarStackView:0x7fc2c6817b10] (active, names: '|':_UIToolbarContentView:0x7fc2c6a5b8f0 )>",
"<NSLayoutConstraint:0x600002175e50 H:[_UIButtonBarStackView:0x7fc2c6817b10]-(0)-| (active, names: '|':_UIToolbarContentView:0x7fc2c6a5b8f0 )>",
"<NSLayoutConstraint:0x6000022019f0 'TB_Leading_Leading' H:|-(8)-[_UIModernBarButton:0x7fc2a5aa8920] (active, names: '|':_UIButtonBarButton:0x7fc2a5aa84d0 )>",
"<NSLayoutConstraint:0x600002201a40 'TB_Trailing_Trailing' H:[_UIModernBarButton:0x7fc2a5aa8920]-(0)-| (active, names: '|':_UIButtonBarButton:0x7fc2a5aa84d0 )>",
"<NSLayoutConstraint:0x600002201e50 'UISV-canvas-connection' UILayoutGuide:0x600003b7d420'UIViewLayoutMarginsGuide'.leading == _UIButtonBarButton:0x7fc2f57117f0.leading (active)>",
"<NSLayoutConstraint:0x600002201ea0 'UISV-canvas-connection' UILayoutGuide:0x600003b7d420'UIViewLayoutMarginsGuide'.trailing == UIView:0x7fc2a5aac8e0.trailing (active)>",
"<NSLayoutConstraint:0x6000022021c0 'UISV-spacing' H:[_UIButtonBarButton:0x7fc2f57117f0]-(0)-[UIView:0x7fc2a5aa8330] (active)>",
"<NSLayoutConstraint:0x600002202210 'UISV-spacing' H:[UIView:0x7fc2a5aa8330]-(0)-[_UIButtonBarButton:0x7fc2a5aa84d0] (active)>",
"<NSLayoutConstraint:0x600002202260 'UISV-spacing' H:[_UIButtonBarButton:0x7fc2a5aa84d0]-(0)-[UIView:0x7fc2a5aac8e0] (active)>",
"<NSLayoutConstraint:0x600002176f30 'UIView-leftMargin-guide-constraint' H:|-(0)-[UILayoutGuide:0x600003b7d420'UIViewLayoutMarginsGuide'](LTR) (active, names: '|':_UIButtonBarStackView:0x7fc2c6817b10 )>",
"<NSLayoutConstraint:0x600002176e40 'UIView-rightMargin-guide-constraint' H:[UILayoutGuide:0x600003b7d420'UIViewLayoutMarginsGuide']-(0)-|(LTR) (active, names: '|':_UIButtonBarStackView:0x7fc2c6817b10 )>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x600002201a40 'TB_Trailing_Trailing' H:[_UIModernBarButton:0x7fc2a5aa8920]-(0)-| (active, names: '|':_UIButtonBarButton:0x7fc2a5aa84d0 )>
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.
I want to have my own background and foreground colors for some views and I am having a bit of trouble. I cannot figure out how to remove the margins around some built-in views. One example is below. The ScrollView portion is always black or white, depending on whether I am I dark mode or not. I've added various colors and borders to see what is going on below. I've also tried adding the modifiers to the Scroll View rather than the TextEditor and it doesn't work at all. If I don't have the .frame modifier on the ScrollView, the TextEditor moves to the top of its frame for some reason. I've played with .contentMargins, .edgeInsets, etc. with no luck
How do I get the TextEditor to fill the entire ScrollView without the margin? Thanks!
import SwiftUI
struct TextEditorView: View
{ @Binding var editString: String
var numberOfLines: Int
var lineHeight: CGFloat
{ UIFont.preferredFont(forTextStyle: .body).lineHeight
}
var viewHeight: CGFloat
{ lineHeight * CGFloat(numberOfLines) + 8
}
var body: some View
{ ScrollView([.vertical], showsIndicators: true)
{ TextEditor(text: $editString)
.border(Color.red, width: 5)
.foregroundStyle(.yellow)
.background(.blue)
.frame(minHeight:viewHeight, maxHeight: viewHeight)
.scrollContentBackground(.hidden)
}
.frame(minHeight:viewHeight, maxHeight: viewHeight)
}
}