I’m trying to add a TextField to the toolbar using .principal placement, and I want it to either fill the screen width or expand based on the surrounding content. However, it’s not resizing as expected — the TextField only resizes correctly when I provide a hardcoded width value. This behavior was working fine in previous versions of Xcode, but seems to be broken in Xcode 26. Not sure if this is an intentional change or a bug. i am using iOS26 beta and Xcode 26 beta
struct ContentView: View {
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, world!")
}
.padding()
.toolbar {
ToolbarItem(placement: .principal) {
HStack {
TextField("Search", text: .constant(""))
.textFieldStyle(.roundedBorder)
.frame(maxWidth: .infinity)
// .frame(width: 300)
Button("cancel") {
}
}
.frame(maxWidth: .infinity)
}
}
}
}
#Preview {
NavigationView {
ContentView()
}
}
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
There appears to be a visual bug when using .searchable in a child view that’s pushed via NavigationLink inside a NavigationStack. Specifically, the search bar appears briefly in the wrong position (or animates in an unexpected way) during the transition to the child view.
This issue does not occur when using NavigationView instead of NavigationStack.
Steps to Reproduce:
Create a TabView with a single tab containing a NavigationStack.
Push from a ContentView to a DetailsView using NavigationLink.
Add a .searchable modifier to both the ContentView and DetailsView.
Run the app and tap a row to navigate to the details view.
Expected Behavior
The search bar in the DetailsView should appear smoothly and in the correct position as the view transitions in, just like it does under NavigationView.
Actual Behavior
When the DetailsView appears, the search bar briefly animates or appears in the wrong location before settling into place. This results in a jarring or buggy visual experience.
Feedback: FB17031212
Here is a reddit thread discussing the issue as well https://www.reddit.com/r/SwiftUI/comments/137epji/navigation_stack_with_search_bar_has_a_bug_and_a/
I hope that an Apple engineer can get this fixed soon. It's frustrating to have new APIs come out with the old deprecated yet there are still obvious bugs two years later.
import SwiftUI
public enum Tab {
case main
}
struct AppTabNavigation: View {
@State private var tabSelection = Tab.main
var body: some View {
TabView(selection: $tabSelection) {
NavigationStack {
ContentView()
}
.tag(Tab.main)
.tabItem {
Label("Main", systemImage: "star")
}
}
}
}
struct ContentView: View {
@State private var searchText = ""
var body: some View {
List(0..<100) { i in
NavigationLink("Select \(i)", value: i)
}
.navigationTitle("Main")
.searchable(text: $searchText)
.navigationDestination(for: Int.self) { i in
DetailsView(i: i)
}
}
}
struct DetailsView: View {
@State private var searchText = ""
let i: Int
// MARK: - Body
var body: some View {
List {
ForEach(0..<10, id: \.self) { i in
Text("Hello \(i)")
}
}
.navigationTitle(i.formatted())
.searchable(text: $searchText)
}
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
Is it not possible to dynamically change or constrain an NSPreferencePane's mainView size? I have looked all over and this doesn't seem to be mentioned anywhere. The most I can seemingly do is set the frame and hope the user doesn't resize the window.
class scor: NSPreferencePane {
override func mainViewDidLoad() {
mainView = NSHostingView(rootView: ContentView())
mainView.frame = NSMakeRect(0, 0, 668, 1048)
}
}
Here is a screenshot, just with a simple webview as a test, note the scrollbar:
My storyboard is just from the default prefpane Xcode template, nothing special. I looked at the header file for NSPreferencePane and came up with nothing. All I can think of is that this is impossible due to the way they are implemented? The only thing we seemingly have access to is mainView, so I can't like constrain the size of mainView to its parent, for example.
Additionally, if I make a new preference pane, and make a button or other view that I choose to resize to fill horizontally and vertically, it does that, but not really? Here is what that looks like:
The behaviour is similar to the previous preference pane, the width does adapt correctly, the height stays the same, forever.
Not that it really matters but I am using macOS 14.7.6 on an M2 air
Hello, I have a question about FocusState, navigationLink and sheet, the code which in navigationLink closure doesn’t work, but work without navigationLink, just like the following code
struct ContentView: View {
var body: some View {
NavigationStack {
// this work
interView()
// this doesn't work
NavigationLink {
interView()
} label: {
Text("into interView")
}
}
}
}
struct interView: View {
@FocusState var focusStateA : Int?
@State var show : Bool = false
@State var text: String = ""
var body: some View {
ScrollView {
VStack {
coreView
Button("Detail") {
show.toggle()
}
}
.sheet(isPresented: $show, content: {
coreView
})
}
}
}
extension interView {
var coreView : some View {
VStack {
VStack {
putdown
TextField("hi", text: $text)
.focused($focusStateA , equals: 1)
}
}
}
var putdown : some View {
Button(action: {
if focusStateA != nil {
focusStateA = nil
print("OK")
} else {
print("It's nil")
}
}, label: {
Text("Put down the keyboard")
})
}
}
and there are some strange phenomena, I must put all view into a scrollview, otherwise, it even doesn’t work without navigationLink
This problem has existed in IOS 18, and now in IOS26 still doesn’t be settled, is it a problem or some character?
Topic:
UI Frameworks
SubTopic:
SwiftUI
I'm using SwiftUI's TextEditor. I'd like to include an undo button in my UI that operates on the TextEditor. I don't see a way to hook this up. You can get the UndoManager from the environment, but this is not the undo manager the TextEditor is using. I know that UITextView uses an undocumented UndoManager (_UITextUndoManager) and I've accessed that before when using a UIViewRepresentable wrapper around UITextView. I'd like to achieve the same with TextEditor.
Topic:
UI Frameworks
SubTopic:
SwiftUI
Using the new floating tab bar with ios18 on ipad with an RTL language, when the tabbar is correctly flipped and the right buttons become left buttons, the buttons are pushed off the screen on initial load but do come back after some navigating / reloading, have recreated in a fresh project.
Hello, we have a requirement where clicking a button will highlight the model, similar to the effect seen by the eyes. However, the eyes do not see it and it is achieved by clicking a button. What should we do? Thank you for your reply
I am using live activity in my app. Functionality is start, update & end events are started from the server. There is one interaction button added using app intent in live activity widget. That button needs to update widget ui locally using activity kit.
Issue is when os receives first start event push then update ui works fine and reflecting on live activity widget but when update notification receives by os after 1 mins then action button stops updating the ui locally.
Can anyone please add some suggestions to fix this.
When my CPMapButton is selected/focused, I would like to be able to provide a focusedImage to correctly show the button when the blue focus is shown. Currently I have:
What do I need to do to create an image that works more like the panning interface buttons?
Hello,
I’m developing an app where I display a SwiftUI view inside a UIHostingController embedded within a UIKit ViewController.
I’m trying to animate the height of the UIHostingController’s view based on a switch’s value, but the SwiftUI view doesn’t animate at all.
Below is a simplified version of my code:
class ViewController: UIViewController {
private lazy var parentView: UIView = {
let view = UIView()
view.backgroundColor = .red
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private lazy var hostingView: UIView = {
let testView = TestView()
let hostingController = UIHostingController(rootView: testView)
let view = hostingController.view!
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private lazy var button: UISwitch = {
let button = UISwitch()
button.addTarget(self, action: #selector(onClickSwitch(sender:)), for: .valueChanged)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
private var hostingViewHeightConstraint: NSLayoutConstraint?
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(parentView)
parentView.addSubview(hostingView)
parentView.addSubview(button)
NSLayoutConstraint.activate([
parentView.topAnchor.constraint(equalTo: view.topAnchor),
parentView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
parentView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
parentView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
NSLayoutConstraint.activate([
hostingView.bottomAnchor.constraint(equalTo: parentView.bottomAnchor),
hostingView.leadingAnchor.constraint(equalTo: parentView.leadingAnchor),
hostingView.trailingAnchor.constraint(equalTo: parentView.trailingAnchor)
])
hostingViewHeightConstraint = hostingView.heightAnchor.constraint(equalTo: parentView.heightAnchor, multiplier: 0.5)
hostingViewHeightConstraint?.isActive = true
NSLayoutConstraint.activate([
button.centerXAnchor.constraint(equalTo: parentView.centerXAnchor),
NSLayoutConstraint(item: button,
attribute: .centerY,
relatedBy: .equal,
toItem: parentView,
attribute: .centerY,
multiplier: 0.25,
constant: 0)
])
}
@objc func onClickSwitch(sender: UISwitch) {
hostingViewHeightConstraint?.isActive = false
let multiplier: CGFloat = sender.isOn ? 0.25 : 0.5
hostingViewHeightConstraint = hostingView.heightAnchor.constraint(equalTo: parentView.heightAnchor, multiplier: multiplier)
hostingViewHeightConstraint?.isActive = true
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded()
}
}
}
I’m looking for the behavior demonstrated in the video below:
Does anyone have suggestions on how to achieve this?
I am currently developing an AR experience using ARKit with SceneKit and am looking to implement functionality that enables:
Zooming into the AR camera feed, ideally leveraging the ultra-wide or telephoto lenses available on supported devices.
Macro-style focus capabilities, allowing users to view and interact with virtual content closely aligned with small or nearby real-world objects (within a few centimeters).
My objective is to ensure that ARKit continues to render the scene accurately while enabling a zoomed-in view or macro-level focus for better detail visibility and alignment.
Could you please advise on:
Whether ARKit currently supports camera zoom or allows access to macro or ultra-wide cameras within an ARSession.
Limitations or considerations when using multi-camera setups in conjunction with ARKit.
Any guidance or references to documentation or sample code would be greatly appreciated.
So I am looking to use a custom NSWindow application (so I can implement some enhanced resizing/dragging behavior which is only possible overriding NSWindow).
The problem is my whole application is currently SwiftUI-based (see the project here: https://github.com/msdrigg/Roam/blob/50a2a641aa5f2fccb4382e14dbb410c1679d8b0c/Roam/RoamApp.swift).
I know there is a way to make this work by dropping my @main SwiftUI app and replacing it with a SwiftUI root view hosted in a standard AppKit root app, but that feels like I'm going backwards.
Is there another way to get access (and override) the root NSWindow for a SwiftUI app?
I would like to have different fill colors in my chart. What I want to achieve is that if the values drop below 0 the fill color should be red. If they are above the fill color should be red. My code looks as follows:
import SwiftUI
import Charts
struct DataPoint: Identifiable {
let id: UUID = UUID()
let x: Int
let y: Int
}
struct AlternatingChartView: View {
enum Gradients {
static let greenGradient = LinearGradient(gradient: Gradient(colors: [.green, .white]), startPoint: .top, endPoint: .bottom)
static let blueGradient = LinearGradient(gradient: Gradient(colors: [.white, .blue]), startPoint: .top, endPoint: .bottom)
}
let data: [DataPoint] = [
DataPoint(x: 1, y: 10),
DataPoint(x: 2, y: -5),
DataPoint(x: 3, y: 20),
DataPoint(x: 4, y: -8),
DataPoint(x: 5, y: 15),
]
var body: some View {
Chart {
ForEach(data) { data in
AreaMark(
x: .value("Data Point", data.x),
y: .value("amount", data.y))
.interpolationMethod(.catmullRom)
.foregroundStyle(data.y < 0 ? Color.red : Color.green)
LineMark(
x: .value("Data Point", data.x),
y: .value("amount", data.y))
.interpolationMethod(.catmullRom)
.foregroundStyle(Color.black)
.lineStyle(StrokeStyle.init(lineWidth: 4))
}
}
.frame(height: 200)
}
}
#Preview {
AlternatingChartView()
}
The result looks like this:
I also tried using
foregroundStyle(by:)
and
chartForegroundStyleScale(_:)
but the result was, that two separate areas had been drawn. One for the below and one for the above zero datapoints.
So, what would be the right approach to have two different fill colors?
I've coded a small raytracer that renders a scene (based on Peter Shirley's tutorial, I just coded it in Swift). The raytracer itself works fine, outputs a PPM file which is correct. However, I was hoping to enclose this in a UI that will update the picture as each pixel value gets updated during the render. So to that end I made a MacOS app, with a basic model-view architecture.
Here is my model:
//
// RGBViewModel.swift
// rtweekend_gui
//
//
import SwiftUI
// RGB structure to hold color values
struct RGB {
var r: UInt8
var g: UInt8
var b: UInt8
}
// ViewModel to handle the RGB array and updates
class RGBViewModel: ObservableObject {
// Define the dimensions of your 2D array
let width = 1200
let height = 675
// Published property to trigger UI updates
@Published var rgbArray: [[RGB]]
init() {
// Initialize with black pixels
rgbArray = Array(repeating: Array(repeating: RGB(r: 0, g: 0, b: 0), count: width), count: height)
}
func render_scene() {
for j in 0..<height {
for i in 0..<width {
// Generate a random color
let r = UInt8.random(in: 0...255)
let g = UInt8.random(in: 0...255)
let b = UInt8.random(in: 0...255)
// Update on the main thread since this affects the UI
DispatchQueue.main.async {
// Update the array
self.rgbArray[j][i] = RGB(r: r, g: g, b: b)
}
}
}
}
and here is my view:
//
// RGBArrayView.swift
// rtweekend_gui
//
//
import SwiftUI
struct RGBArrayView: View {
// The 2D array of RGB values
@StateObject private var viewModel = RGBViewModel()
// Control the size of each pixel
private let pixelSize: CGFloat = 1
var body: some View {
VStack {
// Display the RGB array
Canvas { context, size in
for y in 0..<viewModel.rgbArray.count {
for x in 0..<viewModel.rgbArray[y].count {
let rgb = viewModel.rgbArray[y][x]
let rect = CGRect(
x: CGFloat(x) * pixelSize,
y: CGFloat(y) * pixelSize,
width: pixelSize,
height: pixelSize
)
context.fill(
Path(rect),
with: .color(Color(
red: Double(rgb.r) / 255.0,
green: Double(rgb.g) / 255.0,
blue: Double(rgb.b) / 255.0
))
)
}
}
}
.border(Color.gray)
// Button to start filling the array
Button("Render") {
viewModel.render_scene()
}
.padding()
}
.padding()
.frame(width: CGFloat(viewModel.width) * pixelSize + 40,
height: CGFloat(viewModel.height) * pixelSize + 80)
}
}
// Preview for SwiftUI
struct RGBArrayView_Previews: PreviewProvider {
static var previews: some View {
RGBArrayView()
}
}
The render does work and the image displays, however, I thought I set it up to show the image updating pixel by pixel and that doesn't happen, the image shows up all at once. What am I doing wrong?
Hello,
In a new app I am working on I noticed the FamilyActivityTitleView that displays "ApplicationToken" has wrong (black) color when phone is set to light mode but app is using dark mode via override.
We display user's selected apps and the labels are rendered correctly at first, but then when user updates selection with FamilyActivityPicker, then those newly added apps are rendered with black titles.
The problem goes away when I close the screen and open it again. It also doesn't happen when phone is set to dark theme.
I am currently noticing the issue on iOS 18.4.1.
I have tried various workarounds like forcing white text in the custom label style, forcing re-render with custom .id value but nothing helped.
Is there any way how to fix this?
WKWebView cannot load and display HTTP image resources
Topic:
UI Frameworks
SubTopic:
UIKit
When the perform method of my AppIntent returns the custom view's dialog, and after I click the "Click Test" button, my app will be launched, but this dialog does not close. How can I close it?
struct QuestionResultView: View {
var body: some View {
VStack {
if #available(iOS 17.0, *) {
Button(role:.cancel, intent: OpenAppIntent()) {
Text("Click Test")
}
}
}.frame(height: 300)
}
}
struct OpenAppIntent : AppIntent {
static let title: LocalizedStringResource = "Open my app"
static let openAppWhenRun: Bool = true
static let isDiscoverable: Bool = false;
@MainActor
func perform() async throws -> some IntentResult {
return .result()
}
}
struct OpenPhotoRecognizing: AppIntent {
static let title: LocalizedStringResource = "Read photo"
static let description = IntentDescription("")
static let openAppWhenRun: Bool = false
func perform() async throws -> some IntentResult & ShowsSnippetView & ProvidesDialog{
return .result(dialog: "Demo Test") {
DemoResultView()
}
}
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
Hey,
Anyone knows of a possible way to present a PasteButton in a .confirmationDialog on iOS?
when I try adding it, it's ignored and not displayed with the rest of the buttons
struct MyView: View {
@State var flag: Bool = false
var body: some View {
Text("Some Text")
.confirmationDialog("Dialog", isPresented: $flag) {
Group {
Button("A") {}
Button("B") {}
PasteButton(payloadType: Data.self) { data in
}
}
}
}
}
Something func applicationWillEnterForeground is not getting called for specific iOS 18.3.2
Topic:
UI Frameworks
SubTopic:
UIKit
This was also raised in FB17028569
I have iOS document based app using DocumentGroup. I can create and save documents as expected. All that functionality is fine.
@main
struct FooBarApp: App {
var body: some Scene {
DocumentGroup(newDocument: { FoobarDocument() }) { config in
MainView(document: config.document)
}
The problem is when I open an app document from Files.app or Messages the document is never opened directly into the editor, the document browser interface is always presented and the user must manually select the document to open an editor.
This also happens when I use
UIApplication.shared.requestSceneSessionActivation(nil, userActivity: activity, options: nil)
to open a new scene. The doc isn't opened into my editor.
I believe my plist document types are setup correctly and that my ReferenceFileDocument is setup correctly
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>foobar</string>
</array>
<key>CFBundleTypeIconFile</key>
<string>icon-128</string>
<key>CFBundleTypeIconSystemGenerated</key>
<integer>1</integer>
<key>CFBundleTypeMIMETypes</key>
<array>
<string>application/json</string>
</array>
<key>CFBundleTypeName</key>
<string>Foobar Project</string>
<key>LSHandlerRank</key>
<string>Owner</string>
<key>LSItemContentTypes</key>
<array>
<string>com.digital-dirtbag.foobar</string>
</array>
<key>NSUbiquitousDocumentUserActivityType</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER).ubiquitousdoc</string>
</dict>
</array>
<key>UTExportedTypeDeclarations</key>
<array>
<dict>
<key>UTTypeConformsTo</key>
<array>
<string>public.data</string>
</array>
<key>UTTypeDescription</key>
<string>Foobar Project</string>
<key>UTTypeIconFiles</key>
<array>
<string>icon-128.png</string>
</array>
<key>UTTypeIdentifier</key>
<string>com.digital-dirtbag.foobar</string>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
<array>
<string>foobar</string>
</array>
</dict>
</dict>
The question is does DocumentGroup on iOS even support opening documents directly into the editor view?
I know it works on macOS as expected as I tried this with the demo code and it exhibits the same symptoms. Opening a document from iOS Files.app only gets you as far as the document browser while macOS will open an editor directly.
Topic:
UI Frameworks
SubTopic:
SwiftUI