How to declare functions in Swift? [duplicate] - swiftui

This question already has answers here:
SwiftUI - How can I call a Function in my View?
(4 answers)
Closed 1 year ago.
I want to know how to declare and call functions using SwiftUI, I have written the following code, what is wrong with it?
struct ContentView: View {
var body: some View {
printHello()
}
func printHello() {
print("Hello from function!")
}
}

Everything inside var body: some View { ... } must be a View. Your function printHello() is not a View, so it doesn't work.
You're probably looking for the onAppear modifier, which is called when a View appears.
struct ContentView: View {
var body: some View {
Text("This Text is a View")
.onAppear { /// called when the Text (a View) appears
printHello()
}
}
func printHello() {
print("Hello from function!")
}
}

Related

Is there any way to invoke subview's function in SwiftUI?

Here is an example:
struct ContentView: View {
var body: some View {
VStack {
SubView()
Button("Invoke"){
...// invoke subview's function
}
}
}
}
struct SubView: View{
var body: some View{
Text("SubView")
}
func changeSubView() {
//...
}
}
This is a simplified example. I don't want to use #State to control or pass function as a parameter.
Is there any other way?

Avoid inherited styling inside List Section

When I add my custom widget into List's Section header, the elements inside my widget gets styled. Among others all the text become ALLCAPS. How can I avoid that styling, especially text capitalization?
struct MyHeader: View {
var body: some View {
Text("Hello wOrLd!")
}
}
struct ContentView: View {
var body: some View {
List {
Section(header: MyHeader()) {}
}
}
}
struct MyHeader: View {
var body: some View {
Text("Hello wOrLd!").textCase(.none)
}
}
Maybe it works

SwiftUI - Navigating back to home without nesting?

In the code below, if I use the links to go back and forth between views A and B, I will end up with nested views as shown in the image. The only way I've found to avoid nesting is to never link to a view where a NavigationView is declared - as it is in ViewA below. My question...is there any way to go back to ViewA without the views nesting?
struct ViewA: View {
var body: some View {
NavigationView{
NavigationLink(destination: ViewB()) {
Text("ViewB")
}
}
.navigationBarTitle("ViewA")
}
}
struct ViewB: View {
var body: some View {
NavigationLink(destination: ViewA()) {
Text("ViewA")
}
.navigationBarTitle("ViewB")
}
}
You should not create NavigationLink(destination: ViewA()) because it is not back it creates a new ViewA. Once you navigate to ViewB, the back button will be create for you automatically.
struct ViewA: View {
var body: some View {
NavigationView{
NavigationLink(destination: ViewB()) {
Text("ViewB")
}
}
.navigationBarTitle("ViewA")
}
}
struct ViewB: View {
var body: some View {
Text("ViewB Pure Content")
.navigationBarTitle("ViewB")
}
}
You are nesting views because every time you click ViewA/ViewB it creates a new view object. You can add
#Environment(\.presentationMode) var presentationMode
and call
presentationMode.wrappedValue.dismiss()
when the view button gets pressed you dismiss it.

Button and Text In VStack

I am trying to define the following View in SwiftUI but it is not working:
struct ContentView: View {
var body: some View {
Text("Placeholder")
Button(action: {
// Do something
}) {
Text("Button")
}
}
}
The error is :
Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type
There are also two warnings:
Result of 'Text' initializer is unused
and
Result of 'Button<Label>' initializer is unused
I am trying to code with XCode11 on Mac with OS Catalina. Does anybody know what the problem is?
You forgot to add mentioned VStack
var body: some View {
VStack { // << here !!
Text("Placeholder")
Button(action: {
// Do something
}) {
Text("Button")
}
}
}
You have missed the VStack :
var body: some View {
VStack {
Text("Placeholder")
Button("Button"){ }
}
}

How to print() to Xcode console in SwiftUI?

So I tried to put a print statement while debugging in a SwiftUI View.
print("landmark: \(landmark)")
In the following body.
var body: some View {
NavigationView {
List {
Toggle(isOn: $userData.showFavoritesOnly) {
Text("Favorite only")
}
ForEach(landmarkData) { landmark in
print("landmark: \(landmark)")
if !self.userData.showFavoritesOnly || landmark.isFavorite {
NavigationButton(destination: LandmarkDetail(landmark: landmark)) {
LandmarkRow(landmark: landmark)
}
}
}
}
.navigationBarTitle(Text("Landmarks"))
}
}
Compiler errors out:
So, what is the proper way to print to console in SwiftUI?
EDIT:
I made Landmark conform to CustomStringConvertible:
struct Landmark: Hashable, Codable, Identifiable, CustomStringConvertible {
var description: String { name+"\(id)" }
var id: Int
var name: String
.....
I still get the "String is not convertible to any" error. Should it work now?
You can easily add a print statement anywhere in a function builder by simply storing its return value in a wildcard, effectively ignoring it:
let _ = print("hi!")
No setup or other verbosity needed!
Why does this work while a regular print() doesn't?
The way SwiftUI's #ViewBuilder (and result builders in general) is that they consume any values in a closure that aren't used otherwise (e.g. if you just have 42 on its own line). The print function returns Void (nothing), which the builder would have to build into a view, so it fails. By instead assigning it to a variable (in this case _, basically a variable that you can never access), the Void is never offered to the view builder in the first place.
You could argue the builder should simply accept and ignore Void values, but the idea is that your builder closures should not have side effects (I'd remove print statements after finishing debugging too)—you should not rely on these closures being called at certain times.
Here's a helper Print( ... ) View that acts like a print( ... ) function but within a View
Put this in any of your view files
extension View {
func Print(_ vars: Any...) -> some View {
for v in vars { print(v) }
return EmptyView()
}
}
and use inside of body like so
Print("Here I am", varOne, varTwo ...)
or inside a ForEach {} like so
self.Print("Inside ForEach", varOne, varTwo ...)
Note: you might need to put Print() into a Group {} when combining with existing views
Try right-clicking on the live preview play button and selecting 'Debug Preview from the popup
You can print in the body structure but to do so you have to explicitly return the view you want to render. The body property inside a View is just a computed property like any other in Swift that implicitly returns the view. And just like any other computed property, you can perform operations inside the computed property as long as a value is explicitly returned. For example, this will throw an error when you try to print because there is no explicit return:
struct SomeView: View {
#State var isOpen = false
var body: some View {
print(isOpen) // error thrown here
VStack {
// other view code
}
}
}
But if we explicitly return the view we want then it will work e.g.
struct SomeView: View {
#State var isOpen = false
var body: some View {
print(isOpen) // this ok because we explicitly returned the view below
// Notice the added 'return' below
return VStack {
// other view code
}
}
}
The above will work well if you're looking to view how state or environment objects are changing before returning your view, but if you want to print something deeper down within the view you are trying to return, then I would go with #Rok Krulec answer.
It is possible to use print() remembering that all SwiftUI View content are (a) implicit closures and (b) it is highly recommended to decompose views as much as possible to have simple structure, so it might look like the following...
struct Model: Identifiable {
let value: String
var id: String {
value
}
init (_ value: String) {
self.value = value
}
}
struct TestView: View {
#State var showFavoritesOnly = false
#State var listData: [Model] = [Model("one"), Model("two"), Model("three")]
var body: some View {
NavigationView {
List {
Toggle(isOn: $showFavoritesOnly) {
Text("Favorite only")
}
ForEach(listData) { data in
self.rowView(data: data)
}
}
}
}
private func rowView(data: Model) -> some View {
#if DEBUG
print(">> \(data.value)")
#endif
return NavigationLink(destination: Text("Details")) {
Text("Go next from \(data.value)")
}
}
}
... and right clicking in Preview to select run as Debug Preview we get:
2019-10-31 14:28:03.467635+0200 Test[65344:11155167] [Agent] Received connection, creating agent
2019-10-31 14:28:04.472314+0200 Test[65344:11155168] [Agent] Received display message
>> one
>> two
>> three
You can declare a printing() method that includes print() and returns EmptyView struct.
struct ContentView: View {
#State private var offset = CGSize.zero
func printing(_ items: Any...) -> some View {
let _ = print(items)
return EmptyView()
}
var body: some View {
#if DEBUG
printing(offset) // prints [(0.0, 0.0)]
#endif
ZStack {
Text("Hello")
}
}
}
The safest and easiest way to print while debugging in a SwiftUI View.
extension View {
func Print(_ item: Any) -> some View {
#if DEBUG
print(item)
#endif
return self
}
}
Usage Example:
struct ContentView: View {
var body: some View {
VStack {
ForEach((1...5), id: \.self) { number in
Text("\(number)")
.Print(number)
}
}
}
}
Console output:
1
2
3
4
5
It can be generalized to:
extension View {
func Perform(_ block: () -> Void) -> some View {
block()
return EmptyView()
}
}
So in your example:
ForEach(landmarkData) { landmark in
Perform { print("landmark: \(landmark)") }
if !self.userData.showFavoritesOnly || landmark.isFavorite {
NavigationButton(destination: LandmarkDetail(landmark: landmark)) {
LandmarkRow(landmark: landmark)
}
}
}
Here you go. It will just work like simple print but inside a view.
func printv( _ data : Any)-> EmptyView{
print(data)
return EmptyView()
}
and use it like that
struct ContentView: View {
var body: some View {
VStack() {
Text("hello To SwiftUI")
printv("its easy to code in SwiftUI")
Text("And Good to have you here")
}
}
}
The following extension on View is as intuitive as print because it's made to replicate the default print(_:separator:terminator:) function signature & behavior.
extension View {
func printUI(_ args: Any..., separator: String = " ", terminator: String = "\n") -> EmptyView {
let output = args.map(String.init(describing:)).joined(separator: separator)
print(output, terminator: terminator)
return EmptyView()
}
}
Usage Example:
struct ContentView: View {
var body: some View {
VStack {
printUI("ContentView", "1")
printUI("ContentView", "2", separator: ", ", terminator: "\n.\n.\n")
printUI("ContentView", "3", separator: "; ")
Text("Hello, World!")
}
}
}
Console Output:
ContentView 1
ContentView, 2
.
.
ContentView; 3
EDIT: Debug Preview is no longer supported in the latest versions of Xcode.
Very easy way to debug your Preview:
Open your Swift project in Xcode 11.
Right-click (or Control-click) on the Live Preview button in the bottom right corner of the preview.
Select Debug Preview.
How to debug your SwiftUI previews in Xcode
// Try this, add a 'return' on a view then the 'print' can stay alive in.
struct ContentView: View {
var num: Int = 1
var body: some View {
print(num)
return Text("hello")
}
}
You can't because you're in a computed property. You need for example a button and in the action you define the print. Or work with breakpoints
You can not print in body structure i.e. a structure which is some view type.For print you need to make function out of body structure and call it using button or something else.
This should work
if true {
print(aVar, "xx")
}
return ZStack {
...
}