How does one remove the focus border for a TextField in SwiftUI?In Cocoa, setting the border to "None" in interface builder would remove the border.I've tried using .border with a width of zero, but that does not work. The .border adds another border on top of the focus border.Setting the style also does not do the trick.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
My question is slightly broader, but hopefully this simple use case states the point.I ofthen run in to the problem where my source of truth is a custom type (struct, array of bytes, int, etc.) that I want to edit. I would like to write a view that has a binding to this type so that all the editing logic lives inside this view without the views outside having to worry how it is edited.The simplest example of this is a view that takes a binding to an Int where the user edits it with a TextField. Up to now I've only been able to do this with a custom UI- or NSViewRepresentable implementation. I thought I had a solution today, but it too does not work. It is close enough, that I thought maybe someone can see a path going further.Below is my code. It has an IntView that takes a binding to an Int, and uses state for the strValue. When it first apears, it updates the local state. It then has a method that can be called to update the binding value (this because I cannot get updates as the text field is changing).My contentView creates this view and stores updateValue so that it can be called when the button is pressed. The problem is that view is a value (not a reference), so the intView created in body() is not the same one as that in the .async call (I double-checked this with the print that prints the pointer to each). When updateValue() is called, I get an exception, because I am using the wrong view. The reason for using an .async call is so that I do not change state when body is computed.Can this code somehow be made to work, or is there another solution to writing IntView that takes a binding to an Int?My problem is often more complicated for example when I want to bind to a struct. If I write a custom __ViewRepresentable solution, then I lose a lot of the ease-of-use of swift, and goes back to manual layout, etc.struct IntView: View {
@Binding var value: Int
@State private var strValue: String = ""
var body: some View {
return TextField("Type here", text: $strValue)
.onAppear(perform: { self.strValue = "\(self.value)" })
}
func updateValue() {
value = Int(strValue)!
}
}
struct ContentView: View {
@State var intValue: Int = 12
@State var updateValue: (() -> Void)?
var body: some View {
let intView = IntView(value: $intValue)
withUnsafePointer(to: intView) { print("value at first @\($0)") }
DispatchQueue.main.async {
withUnsafePointer(to: intView) { print("value in async @\($0)") }
self.updateValue = intView.updateValue
}
return VStack {
Text("\(intValue)")
intView
Button(action: {
self.updateValue!()
}, label: { Text("Get Value") })
}
.padding()
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
I am trying to implement a simple Table with a TextField that makes it possible to edit the data.
Below is a very simple example where I am trying to do this. It works, but it becomes very unresponsive as the number of people increases.
The example as it is, has 1,000 people. It is very slow when a TextField gets focus and is used to edit something. Strangely, it also gets very slow when you scroll through an entry that has been edited. It crashes completely when 10,000 people is used.
I found this similar question on the web, but it is not answered.
What should I do to implement an editable Table like this?
struct ContentView: View {
struct Person: Identifiable {
var givenName: String
var familyName: String
let id = UUID()
}
@State private var people = [Person].init(repeating: Person(givenName: "Name", familyName: "Family"), count: 1000)
var body: some View {
Table($people) {
TableColumn("Given Name") { $person in TextField("Name", text: $person.givenName) }
TableColumn("Family Name") { $person in TextField("Family Name", text: $person.familyName) }
TableColumn("Full Name") { $person in Text("\(person.givenName) \(person.familyName)")}
}
}
}
I am doing text replacement in a SwiftUI TextField as the user types. This works fine when the cursor is at the end of the input, but fails when the user moves the cursor to the middle and start typing. As soon as a correction is made, the cursor jumps to the end of the string moving the user's cursor away from where they were editing.
Below is a simple example of a view doing text replacement. Is it possible to get the cursor position inside the onChange modifier, and preserve it without custom wrapping a UITextView. I've done that, and it creates other problems.
struct ContentView: View {
@State private var input: String = ""
var body: some View {
VStack {
TextField("", text: $input)
.onChange(of: input) {
input = input.replacingOccurrences(of: "*", with: "×")
input = input.replacingOccurrences(of: "/", with: "÷")
input = input.replacingOccurrences(of: "pi", with: "π")
}
}
.padding()
}
}
I am trying to create a standard stepper with text field in swiftUI, but it does not seem to exist.I need something that looks like this:Do I have to create my own view, or is something already available?I tried an HStack with Text, TextField and stepper, but this does not align properly when placed in a form, and the stepper and text field cannot have a binding to the same value.Any ideas on how to implement this?
The new SwiftUI introduces the new Menu - https://developer.apple.com/documentation/swiftui/menu item but I cannot find any complete examples showing how to use it.
I did find an article (cannot link to it here) on how to use Menu but it is connected to a toolbar item only and does not change the menubar.
I would like to add a menu item to the menubar in macOS using a SwiftUI App. Any examples of how to do this would be great.
I was hoping to use swift Mirror to create an extension that can change the properties of a struct.
It seems however that mutating the child items of the mirror is creating new instances and mutating those instead of the members of the method.
Below is a playground that shows my problem.
Can I use Mirror to achieve the goal of setting member values of structs that implement the given protocol, or should I take a different approach (and if so what)?
import Cocoa
struct Point {
var x: Int = 0
var y: Int = 0
}
protocol Shape {
var origin: Point { get }
}
extension Shape {
//: The hope is to have a generic function that will set the value of all parameters of type 'Point' but it is not working. The fact that I do not need "mutating" for this function is another clue that it will not mutate the members of the Shape.
mutating func clearAllPoints() {
let mirror = Mirror(reflecting: self)
for child in mirror.children {
// It seems the line below creates a new point instance and it is not the same member of self.
if var point = child.value as? Point {
point.x = 0
point.y = 0
}
}
}
func printAllPoints() {
let mirror = Mirror(reflecting: self)
for child in mirror.children {
if let point = child.value as? Point {
print("\(child.label!) = (x: \(point.x), y: \(point.y)")
}
}
}
}
struct Rectangle: Shape {
var origin = Point()
var corner = Point()
init() {
origin = Point(x: 10, y: 10)
corner = Point(x: 20, y: 30)
}
}
var rect = Rectangle()
//: rect has just been initialised, and the line below correctly prints all Points as initialised.
rect.printAllPoints()
//: Hope is that the line below will clear all Points but ...
rect.clearAllPoints()
//: ... it does not. The line below prints all Points with exactly the same values.
rect.printAllPoints()
I have a class that I cannot change to ObservableObject with Published members.
I tried getting around this by writing my own Binding. Although the value is updated correctly, the UI is not. Why is this.
Below is a simple demo view. When it is run and the toggle is clicked, it will print out correctly that the value is changed, but the UI does not update. Why?
import SwiftUI
class BoolWrapper {
public var value = false {
didSet {
print("Value changed to \(value)")
}
}
}
let boolWrapper = BoolWrapper()
struct ContentView: View {
var body: some View {
Toggle(isOn: Binding(get: {
return boolWrapper.value
}, set: { value in
boolWrapper.value = value
}), label: { Text("Toggle") })
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
I am trying out the new TextField selection ability on macOS but it crashes in various different ways with extremely large stack traces. Looks like it is getting into re-entrant function calls.
A similar problem is described on the SwiftUI forums with no responses yet.
Here is my simple example
struct ContentView: View {
@State private var text: String = ""
@State private var selection: TextSelection?
var body: some View {
TextField("Message", text: $text, selection: $selection)
.padding()
}
}
Setting text to a value like "Hallo World" causes an instant crash as soon as you start typing in the TextField.
Setting text empty (as in example above) lets you edit the text but as it crashes as soon as you commit it (press enter).
Any workarounds or fixes?
I would like to keep my layout the same, and only rotate views in-place when the screen orientation changes.Below is a simple example of what I am trying to acieve. It shows to TestViews horizontally when in portrait mode, and vertically when in landscape mode.I've made sure that the views themselve does not get re-created in the hope that it would only animate the difference in layout between portrait and landscape, but it makes the views very small, and then animate them in from the corner of the screen.What I am trying to acieve, is for each view to effectively rotate by 90 degrees when the orientation changes. Is it possible in swiftUI?[In my example below, I've hacked my AppDelegate to be my model to get rotation notifications from a publisher in it. This needs to be added for the example to work.]struct TestView: View {
var text: String
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: 25.0, style: .continuous)
.foregroundColor(Color(red: 0.2, green: 0.2, blue: 0.2))
Text(verbatim: text)
.font(.system(size: 95))
.foregroundColor(.white)
}.aspectRatio(1.0, contentMode: .fit)
}
}
struct ContentView: View {
@EnvironmentObject var model : AppDelegate
private let testViews: [TestView] = (0...1).map { TestView(text: "\($0)") }
var body: some View {
ZStack {
if !model.isPotrait {
HStack {
VStack {
testViews[0]
testViews[1]
}
}
} else {
VStack {
HStack {
testViews[0]
testViews[1]
}
}
}
}.padding()
}
}
I have a program where I need to handle Edit>Copy when the first responder cannot.
I've added the following to my AppDelegate:
@IBAction @objc func copy(_ sender: Any?) {
// My code here...
}
But Edit>Copy is greyed out on the menu unless a TextField has focus and it has text selected.
How do I get my copy function called when the text field has focus but does not have text selected (or any other case where the current view with focus cannot handle copy)?
I would like to implement a global copy command for my app. The code below is an attempt at achieving this but does not work.
struct ContentView: View {
@State private var name = ""
var body: some View {
VStack {
Text("Hallo \(name)")
TextField("Please enter your name", text: $name)
}
.onCopyCommand(perform: {
print("You got to onCopy")
var items = [NSItemProvider]()
let stringData = "Hallo \(name)".data(using: .utf8)!
items.append(NSItemProvider(item: stringData as NSData, typeIdentifier: kUTTypePlainText as String))
return items
})
}
}
When the user selects something in the TextField, then using the copy menu should copy that text to the clipboard but when it has nothing selected, then I want to copy "Hallo" and the name to the clipboard.
As you can see, I tried using the onCopyCommand but Copy is always grayed out.
Any ideas on how I can enable Copy on the menu, and handle it when the TextField does not have anything selected?
I used to get an e-mail when people replied to my posts but that is no longer working (I do not know when it broke).
I cannot find where it needs to be enabled. Has it been removed? If not, where is it enabled?
I need to do a bit of customisation on a UITextView so I am creating a custom UIViewRepresentable to wrap the UITextView.
One of these is that the input should be centred and not wrap.
Searching on how to disable wrapping gives various conflicting recommendations, from not using UITextView to wrapping it in a UIScrollView. None of these seem to work reliably.
It seems like all that is required, is setting the size of the text container to be sufficiently wide but this is also not working. Below is what I've tried so far but it does not wrap the view.
The InputView also seems to take up the entire height of the screen. I have a feeling this is fundamentally part of my problem.
What am I missing?
import SwiftUI
struct InputView: UIViewRepresentable {
@Binding var text: String
typealias UIViewType = UITextView
func makeUIView(context: Context) -> UIViewType {
// Setup text view:
// ----------------
let textView = UITextView()
textView.textAlignment = .center
textView.delegate = context.coordinator
textView.font = UIFont.systemFont(ofSize: 72)
textView.textContainer.widthTracksTextView = false
textView.textContainer.size = CGSize(width: 20000, height: CGFloat.greatestFiniteMagnitude)
textView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
return textView
}
func makeCoordinator() -> InputView.Coordinator {
return Coordinator(self)
}
func updateUIView(_ textView: UIViewType, context: Context) {
if textView.text != text {
textView.text = text
}
}
class Coordinator: NSObject, UITextViewDelegate {
var parent: InputView
init(_ parent: InputView) {
self.parent = parent
}
func textViewDidChange(_ textView: UITextView) {
parent.text = textView.text
}
}
}
struct ContentView: View {
@State private var input: String = "ShouldNotWrapButScrollHorizontally"
var body: some View {
InputView(text: $input)
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Reading other questions and searching on the web, I am clearly missing something very obvious.
I am trying to make an app preview video for iOS. I've followed Creating Videos for App Previews to record a video on my iPhone 13. This gives me a video with a resolution of 2532 x 1170 (as expected).
The App preview specifications states that the native iPhone 13 resolution is 2436 x 1125 and that the accepted resolution is 1920 x 886.
Why is the app preview specification native resolution different from the actual iPhone 13 resolution? Am I missing some insets?
When I use Quick Time to save my video as 1080p then I get an output resolution of 1920 x 888 (it seems to be rounding up since the perfect scale would have been 1920 x 887,2037915).
I am unable to see how I can get to the accepted native resolution of 2436 x 1125 or how I can resample it to 1920 x 886.
I get the exact same results using the simulator.
How do I create a preview video in the accepted resolutions?