Adding a TextField to NavigationBar with SwiftUI - swift

I've been fooling around with Xcode 11 and SwiftUI for the past few hours, attempting to implement a TextField in the NavigationBar. Generally, the first "Hello, World"-type application I build is a simple web browser: TextField and WKWebView.
However, I'm having an exceptionally difficult time trying to implement the TextField in a fixed .inline NavigationBar. Furthermore, I can't seem to find a single tutorial or piece of code anywhere online. I've gone through pages and pages of Google, as well as projects on GitHub, with no luck.
The only results that mention this topic in specific are Reddit threads and forum discussion posts – all of which ask the same question: "Has anyone been able to successfully implement a TextField in the NavigationBar?" No one has yet to respond with a solution.
Here's my current ContentView.swift – I have removed all of my programmatic attempts at implementing a TextField as it either crashes or throws errors:
import SwiftUI
import WebKit
let address = "https://developer.apple.com"
struct ContentView: View {
var body: some View {
NavigationView {
VStack {
WebView(request: URLRequest(url: URL(string: address)!))
.edgesIgnoringSafeArea(.bottom)
.edgesIgnoringSafeArea(.leading)
.edgesIgnoringSafeArea(.trailing)
}
.navigationBarTitle("TextField Placeholder", displayMode: NavigationBarItem.TitleDisplayMode.inline)
}
}
}
struct WebView: UIViewRepresentable {
let request: URLRequest
func makeUIView(context: Context) -> WKWebView {
return WKWebView()
}
func updateUIView(_ uiView: WKWebView, context: Context) {
uiView.load(request)
}
}

I don't know if it's exactly what you're trying to achieve, I think it might be a good solution:
import SwiftUI
import WebKit
let address = "https://developer.apple.com"
struct ContentView: View {
#State private var text = ""
var body: some View {
NavigationView {
GeometryReader { geometry in
VStack {
WebView(request: URLRequest(url: URL(string: address)!))
.edgesIgnoringSafeArea(.bottom)
.edgesIgnoringSafeArea(.leading)
.edgesIgnoringSafeArea(.trailing)
}
.navigationBarItems(leading:
HStack {
TextField("Type something here...", text: self.$text)
.background(Color.yellow)
}
.padding()
.frame(width: geometry.size.width)
.background(Color.green)
)
}
}
}
}
struct WebView: UIViewRepresentable {
let request: URLRequest
func makeUIView(context: Context) -> WKWebView {
return WKWebView()
}
func updateUIView(_ uiView: WKWebView, context: Context) {
uiView.load(request)
}
}
#if DEBUG
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif
Copy-paste the code here above and let me know if I can try to improve my solution with something else. I coloured a couple of views of green and yellow just for a matter of debugging.

There is a new method in iOS 14+ that populates the toolbar or navigation bar with the specified items:
func toolbar<Content>(content: () -> Content) -> some View where Content : ToolbarContent

NavigationView {
GeometryReader { geometry in
ZStack {
Text("Hello")
}
.navigationBarTitle(" ", displayMode: .inline)
.navigationBarItems(leading:
HStack {
TextField("Seach for products, brands and more", text: self.$searchText)
}
.frame(width: geometry.size.width - 35,
height: 38,
alignment: .center)
.background(Color.white)
)
.background(NavigationConfigurator { nc in
nc.navigationBar.barTintColor = UIColor(red: 104.0/255.0, green: 194.0/255.0, blue: 25.0/255.0, alpha: 1.0)
})
}
}
.navigationViewStyle(StackNavigationViewStyle())
struct NavigationConfigurator: UIViewControllerRepresentable {
var configure: (UINavigationController) -> Void = { _ in }
func makeUIViewController(context: UIViewControllerRepresentableContext<NavigationConfigurator>) -> UIViewController {
UIViewController()
}
func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<NavigationConfigurator>) {
if let nc = uiViewController.navigationController {
self.configure(nc)
}
}
}

Related

How to clean PKCanvas from strokes when I leave the screen?

I have a basic app, a Main View with links to Drawing View. When I go to the Drawing View №1 and paint something with Apple Pencil, then go back to Main View, then go back to Drawing View №1 - I still see my painting. It stayed in the memory.
Question: What is a proper way to free the memory from PKCanvas and it's strokes when leaving the view?
I know I can "remove" the drawing by assigning canvasView.drawing = PKDrawing() a new blank drawing. But does it really solve the problem of keeping junk in the memory?
Here is my bare-minimum code:
import SwiftUI
import PencilKit
struct ContentView: View {
var body: some View {
NavigationStack {
VStack {
NavigationLink(destination: DrawingView()) {
Text("Go to Drawing #1")
}
.padding()
NavigationLink(destination: DrawingView()) {
Text("Go to Drawing #2")
}
.padding()
}
}
}
}
struct DrawingView: View {
#State private var canvasView = PKCanvasView()
var body: some View {
PKCanvasViewRepresentable(canvasView: $canvasView)
.frame(width: 500, height: 500)
.border(Color.blue)
}
}
struct PKCanvasViewRepresentable: UIViewRepresentable {
#Binding var canvasView: PKCanvasView
func makeUIView(context: Context) -> PKCanvasView {
canvasView.tool = PKInkingTool(.pen, color: .black, width: 26)
canvasView.becomeFirstResponder()
canvasView.delegate = context.coordinator
return canvasView
}
func updateUIView(_ canvasView: PKCanvasView, context: Context) { }
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, PKCanvasViewDelegate, UIPencilInteractionDelegate {
var canvas: PKCanvasViewRepresentable
init(_ canvas: PKCanvasViewRepresentable) {
self.canvas = canvas
}
func canvasViewDrawingDidChange(_ canvasView: PKCanvasView) {
print("canvasViewDrawingDidChange()")
}
}
}

How to make a text appear on the screen after pressing the button?

I want to make the text display on the screen according to the different scenes after pressing the button. For example, if model A is displayed, text "A" will be appeared on the screen. Similarly, if model B is displayed, text "B" will also be appeared. I am currently creating Augmented Reality app using SwiftUI interface and RealityKit but not sure what to do in the next step.
Here is my code:
import SwiftUI
import RealityKit
struct ContentView : View {
#State var arView = ARView(frame: .zero)
var body: some View {
ZStack {
ARViewContainer(arView: $arView)
HStack {
Spacer()
Button("information") {
print(self.arView.scene.name)
print(arView.scene.anchors.startIndex)
print(arView.scene.anchors.endIndex)
}
Spacer()
Button("remove") {
stop()
}
Spacer()
}
} .edgesIgnoringSafeArea(.all)
}
func stop() {
arView.scene.anchors.removeAll()
}
}
struct ARViewContainer: UIViewRepresentable {
#Binding var arView: ARView
func makeUIView(context: Context) -> ARView {
let boxAnchor = try! Experience1.loadBox()
let crownAnchor = try! Experience1.loadCrown()
arView.scene.anchors.append(boxAnchor)
arView.scene.anchors.append(crownAnchor)
return arView
}
func updateUIView(_ uiView: ARView, context: Context) { }
}
From the code above, if boxAnchor and crownAnchor and displayed, text "Box" and "Crown" will be appeared on the screen respectively. Anyone who knows how to do that please guide me or suggest a tutorial that I can use to study.
Sorry if I use the wrong technical terms. Thank you
Use Combine's reactive subscriber and MVVM's bindings to update string values for Text views.
import SwiftUI
import RealityKit
import Combine
struct ContentView : View {
#State private var arView = ARView(frame: .zero)
#State private var str01: String = "...some text..."
#State private var str02: String = "...some text..."
var body: some View {
ZStack {
ARViewContainer(arView: $arView, str01: $str01, str02: $str02)
.ignoresSafeArea()
VStack {
Spacer()
Text(str01)
.foregroundColor(.white)
.font(.largeTitle)
Divider()
Text(str02)
.foregroundColor(.white)
.font(.largeTitle)
Spacer()
}
}
}
}
The miracle happens in the escaping closure of subscribe(to:) instance method. What will be the conditions in the if-statements is up to you.
struct ARViewContainer: UIViewRepresentable {
#Binding var arView: ARView
#Binding var str01: String
#Binding var str02: String
#State var subs: [AnyCancellable] = []
func makeUIView(context: Context) -> ARView {
let boxAnchor = try! Experience.loadBox()
let crownAnchor = try! Experience.loadCrown()
print(arView.scene.anchors.count)
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
arView.scene.anchors.append(boxAnchor)
arView.scene.anchors.append(crownAnchor)
print(arView.scene.anchors.count)
}
return arView
}
func updateUIView(_ view: ARView, context: Context) {
DispatchQueue.main.async {
_ = view.scene.subscribe(to: SceneEvents.DidAddEntity.self) { _ in
if view.scene.anchors.count > 0 {
if view.scene.anchors[0].isAnchored {
str01 = "Crown"
str02 = "Cube"
}
}
}.store(in: &subs)
}
}
}

ARKit camera tracking state can’t show on SwiftUI

I’m trying to show the camera tracking state info on top of device screen, but still get errors for all my efforts. I’m very confused with how ARView works with SwiftUI, for showing AR experience and adding button icons on top of it is simple, but to getting data from session just looks more work need to be done, could someone help me this? Thanks!
Error in ViewModel: ‘description is a get-only property’
Content View
import SwiftUI
import ARKit
import RealityKit
struct ContentView: View {
#StateObject var vm = ViewModel()
var body: some View {
ZStack{
ARViewContainer()
.edgesIgnoringSafeArea(.all)
.environmentObject(vm)
VStack{
Text(vm.sessionInfoLabel)
.font(.title3)
.foregroundColor(.red)
Spacer()
HStack{
Button{
} label: {
Image(systemName: "person.2")
.padding()
.font(.title)
}
Spacer()
Button{
} label: {
Image(systemName: "target")
.padding()
.font(.title)
}
}
.padding()
}
}
}
}
struct ARViewContainer: UIViewRepresentable {
#EnvironmentObject var vm: ViewModel
func makeUIView(context: Context) -> ARView {
return vm.arView
}
func updateUIView(_ uiView: ARView, context: Context) {
}
}
ViewModel
import SwiftUI
import ARKit
import RealityKit
class ViewModel: ObservableObject {
#Published var arView: ARView
var sessionInfoLabel = ""
init() {
arView = ARView.init(frame: .zero)
let config = ARWorldTrackingConfiguration()
config.planeDetection = .horizontal
arView.session.delegate = arView
arView.session.run(config)
}
}
extension ARView: ARSessionDelegate {
public func session(_ session: ARSession, cameraDidChangeTrackingState camera: ARCamera) {
camera.trackingState.description = ViewModel().sessionInfoLabel
}
}
extension ARCamera.TrackingState: CustomStringConvertible {
public var description: String {
switch self {
case .normal:
return "Normal"
case .notAvailable:
return "Not Available"
case .limited(.initializing):
return "Initializing"
case .limited(.excessiveMotion):
return "Excessive Motion"
case .limited(.insufficientFeatures):
return "Insufficient Features"
case .limited(.relocalizing):
return "Relocalizing"
case .limited:
return "Unspecified Reason"
}
}
}

Display UIViewRepresentable as a navigationBarItem in SwiftUI

I can get a button to display in the navigationbaritems in SwiftUI no problem.
I want to display a wrapped UIKit view in the same.
This is a minimal example of a real problem. I want a 100 * 4 UIView displayed as a trailing navigationbaritems.
Here is my code:
struct ContentView: View {
var body: some View {
NavigationView {
VStack {
Text("stack overflow test")
}
.navigationBarItems(trailing: TestView())
.navigationTitle("Navigation")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct TestView: UIViewRepresentable {
func makeUIView(context: Context) -> UIView {
let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 4))
view.backgroundColor = .red
return view
}
func updateUIView(_ uiView: UIView, context: Context) {
}
}
Right now nothing displays in the top-right hand corner of the navigation bar. Why might this be?
Instead of setting frame inside the UIViewRepresentable, set frame in navigationBarItems ContentView
Tested in Xcode 12.3 with iOS 14.3
struct ContentView: View {
var body: some View {
NavigationView {
VStack {
Text("stack overflow test")
}
.navigationBarItems(trailing: TestView().frame(width: 100, height: 4)) //< === Here
.navigationTitle("Navigation")
}
}
}
struct TestView: UIViewRepresentable {
func makeUIView(context: Context) -> UIView {
let view = UIView() //< === Remove From Here
view.backgroundColor = .red
return view
}
func updateUIView(_ uiView: UIView, context: Context) {
}
}
Note :
From iOS 14.5 navigationBarItems is deprecated. Use ToolbarItem
struct ContentView: View {
var body: some View {
NavigationView {
VStack {
Text("stack overflow test")
}
.toolbar { //< === Here
ToolbarItem(placement: .navigationBarTrailing) {
TestView().frame(width: 100, height: 4)
}
}
.navigationTitle("Navigation")
}
}
}

Change background color of TextEditor in SwiftUI

TextEditor seems to have a default white background. So the following is not working and it displayed as white instead of defined red:
var body: some View {
TextEditor(text: .constant("Placeholder"))
.background(Color.red)
}
Is it possible to change the color to a custom one?
iOS 16
You should hide the default background to see your desired one:
TextEditor(text: .constant("Placeholder"))
.scrollContentBackground(.hidden) // <- Hide it
.background(.red) // To see this
iOS 15 and below
TextEditor is backed by UITextView. So you need to get rid of the UITextView's backgroundColor first and then you can set any View to the background.
struct ContentView: View {
init() {
UITextView.appearance().backgroundColor = .clear
}
var body: some View {
List {
TextEditor(text: .constant("Placeholder"))
.background(.red)
}
}
}
Demo
You can find my simple trick for growing TextEditor here in this answer
Pure SwiftUI solution on iOS and macOS
colorMultiply is your friend.
struct ContentView: View {
#State private var editingText: String = ""
var body: some View {
TextEditor(text: $editingText)
.frame(width: 400, height: 100, alignment: .center)
.cornerRadius(3.0)
.colorMultiply(.gray)
}
}
Update iOS 16 / SwiftUI 4.0
You need to use .scrollContentBackground(.hidden) instead of UITextView.appearance().backgroundColor = .clear
https://twitter.com/StuFFmc/status/1556561422431174656
Warning: This is an iOS 16 only so you'll probably need some if #available and potentially two different TextEditor component.
extension View {
/// Layers the given views behind this ``TextEditor``.
func textEditorBackground<V>(#ViewBuilder _ content: () -> V) -> some View where V : View {
self
.onAppear {
UITextView.appearance().backgroundColor = .clear
}
.background(content())
}
}
Custom Background color with SwiftUI on macOS
On macOS, unfortunately, you have to fallback to AppKit and wrap NSTextView.
You need to declare a view that conforms to NSViewRepresentable
This should give you pretty much the same behaviour as SwiftUI's TextEditor-View and since the wrapped NSTextView does not draw its background, you can use the .background-ViewModifier to change the background
struct CustomizableTextEditor: View {
#Binding var text: String
var body: some View {
GeometryReader { geometry in
NSScrollableTextViewRepresentable(text: $text, size: geometry.size)
}
}
}
struct NSScrollableTextViewRepresentable: NSViewRepresentable {
typealias Representable = Self
// Hook this binding up with the parent View
#Binding var text: String
var size: CGSize
// Get the UndoManager
#Environment(\.undoManager) var undoManger
// create an NSTextView
func makeNSView(context: Context) -> NSScrollView {
// create NSTextView inside NSScrollView
let scrollView = NSTextView.scrollableTextView()
let nsTextView = scrollView.documentView as! NSTextView
// use SwiftUI Coordinator as the delegate
nsTextView.delegate = context.coordinator
// set drawsBackground to false (=> clear Background)
// use .background-modifier later with SwiftUI-View
nsTextView.drawsBackground = false
// allow undo/redo
nsTextView.allowsUndo = true
return scrollView
}
func updateNSView(_ scrollView: NSScrollView, context: Context) {
// get wrapped nsTextView
guard let nsTextView = scrollView.documentView as? NSTextView else {
return
}
// fill entire given size
nsTextView.minSize = size
// set NSTextView string from SwiftUI-Binding
nsTextView.string = text
}
// Create Coordinator for this View
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
// Declare nested Coordinator class which conforms to NSTextViewDelegate
class Coordinator: NSObject, NSTextViewDelegate {
var parent: Representable // store reference to parent
init(_ textEditor: Representable) {
self.parent = textEditor
}
// delegate method to retrieve changed text
func textDidChange(_ notification: Notification) {
// check that Notification.name is of expected notification
// cast Notification.object as NSTextView
guard notification.name == NSText.didChangeNotification,
let nsTextView = notification.object as? NSTextView else {
return
}
// set SwiftUI-Binding
parent.text = nsTextView.string
}
// Pass SwiftUI UndoManager to NSTextView
func undoManager(for view: NSTextView) -> UndoManager? {
parent.undoManger
}
// feel free to implement more delegate methods...
}
}
Usage
ContenView: View {
#State private var text: String
var body: some View {
VStack {
Text("Enter your text here:")
CustomizableTextEditor(text: $text)
.background(Color.red)
}
.frame(minWidth: 600, minHeight: 400)
}
}
Edit:
Pass reference to SwiftUI UndoManager so that default undo/redo actions are available.
Wrap NSTextView in NSScrollView so that it is scrollable. Set minSize property of NSTextView to enclosing SwiftUIView-Size so that it fills the entire allowed space.
Caveat: Only first line of this custom TextEditor is clickable to enable text editing.
This works for me on macOS
extension NSTextView {
open override var frame: CGRect {
didSet {
backgroundColor = .clear
drawsBackground = true
}
}
}
struct ContentView: View {
#State var text = ""
var body: some View {
TextEditor(text: $text)
.background(Color.red)
}
Reference this answer
To achieve this visual design here is the code I used.
iOS 16
TextField(
"free_form",
text: $comment,
prompt: Text("Type your feedback..."),
axis: .vertical
)
.lineSpacing(10.0)
.lineLimit(10...)
.padding(16)
.background(Color.themeSeashell)
.cornerRadius(16)
iOS 15
ZStack(alignment: .topLeading) {
RoundedRectangle(cornerRadius: 16)
.foregroundColor(.gray)
TextEditor(text: $comment)
.padding()
.focused($isFocused)
if !isFocused {
Text("Type your feedback...")
.padding()
}
}
.frame(height: 132)
.onAppear() {
UITextView.appearance().backgroundColor = .clear
}
You can use Mojtaba's answer (the approved answer). It works in most cases. However, if you run into this error:
"Return from initializer without initializing all stored properties"
when trying to use the init{ ... } method, try adding UITextView.appearance().backgroundColor = .clear to .onAppear{ ... } instead.
Example:
var body: some View {
VStack(alignment: .leading) {
...
}
.onAppear {
UITextView.appearance().backgroundColor = .clear
}
}
Using the Introspect library, you can use .introspectTextView for changing the background color.
TextEditor(text: .constant("Placeholder"))
.cornerRadius(8)
.frame(height: 100)
.introspectTextView { textView in
textView.backgroundColor = UIColor(Color.red)
}
Result
import SwiftUI
struct AddCommentView: View {
init() {
UITextView.appearance().backgroundColor = .clear
}
var body: some View {
VStack {
if #available(iOS 16.0, *) {
TextEditor(text: $viewModel.commentText)
.scrollContentBackground(.hidden)
} else {
TextEditor(text: $viewModel.commentText)
}
}
.background(Color.blue)
.frame(height: UIScreen.main.bounds.width / 2)
.overlay(
RoundedRectangle(cornerRadius: 5)
.stroke(Color.red, lineWidth: 1)
)
}
}
It appears the UITextView.appearance().backgroundColor = .clear trick in IOS 16,
only works for the first time you open the view and the effect disappear when the second time it loads.
So we need to provide both ways in the app. Answer from StuFF mc works.
var body: some View {
if #available(iOS 16.0, *) {
mainView.scrollContentBackground(.hidden)
} else {
mainView.onAppear {
UITextView.appearance().backgroundColor = .clear
}
}
}
// rename body to mainView
var mainView: some View {
TextEditor(text: $notes).background(Color.red)
}