Add Sample View to PreviewProvider for Custom Wrapper View - swift

I have created a "wrapper" view to handle some standard branding like background color, etc which takes a View as a parameter, but I can't figure out how to pass a sample View in PreviewProvider to see it live in Xcode. This wrapper view works when I build it in the simulator - I just can't figure out how to preview it.
Wrapper View
import SwiftUI
struct BackgroundView<Content: View>: View {
let contentView: Content
init(#ViewBuilder content: #escaping () -> Content) {
self.contentView = content()
}
var body: some View {
ZStack {
GeometryReader { geo in
HStack {
Spacer()
Image("Background Watermark")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 0.7 * geo.size.width, height: geo.size.height, alignment: .topLeading)
}
}
VStack {
self.contentView
}
}
.background(Color("Purple"))
.edgesIgnoringSafeArea(.top)
}
}
// This is where I'm struggling
struct BackgroundView_Previews: PreviewProvider {
static var previews: some View {
BackgroundView(content: ... )
}
}
What I've Tried
I tried passing a simple Text to it, but get Cannot convert value of type 'Text' to expected argument type '() -> Content'
static var previews: some View {
BackgroundView(content: Text("Hello, world"))
}
Then I tried passing a function that returns some View thinking the closure was the issue, but I get Instance member 'sampleTextView' cannot be used on type 'BackgroundView_Previews':
func sampleTextView() -> some View {
Text("Hello world")
}
static var previews: some View {
BackgroundView(content: sampleTextView)
}
Any idea what I'm doing wrong or how to load up a simple Text view just to be able to preview this?

It is expected to be closure, like
static var previews: some View {
BackgroundView(content: { Text("Hello, world") })
}
or
static var previews: some View {
BackgroundView {
Text("Hello, world")
}
}

Related

In SwiftUI, how can I put the navigation bar in the inner view?

In SwiftUI I want to implement the following view. But I have no idea how I can put the navigation bar in the white view inside. Because it is placed on top of the purple view by default.
import SwiftUI
struct ContentView: View {
var body: some View {
ZStack {
Color.purple
WhiteView() // the white view
.padding(.top, 30)
.padding()
}
.edgesIgnoringSafeArea(.all)
}
}
import SwiftUI
struct WhiteView: View {
var body: some View {
Color.white
.cornerRadius (12)
}
}
struct WhiteView_Previews: PreviewProvider {
static var previews: some View {
WhiteView()
}
}
Here is possible approach - use NavigationView over color view, so it takes frame of parent view but not full screen
Tested with Xcode 12.4 / iOS 14.4
struct WhiteView: View {
var body: some View {
Color.white
.overlay(NavigationView {
NavigationLink("Test", destination: Text("Details"))
})
.cornerRadius (12)
}
}
I took your code, stuck it in a NavigationView, added a .navigationTitle, .toolbar and ToolBarItem and this is the View I got:
Code:
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
ZStack {
Color.purple
WhiteView() // the white view
.padding(.top, 30)
.padding()
}
.edgesIgnoringSafeArea(.all)
.navigationTitle("Your Friends")
.toolbar {
ToolbarItem {
Text("Right Button")
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct WhiteView: View {
var body: some View {
Color.white
.cornerRadius (12)
}
}
What, exactly is your question/problem? Everything is in the white area.

Xcode preview doesn't work with generic view

I want to use generic subview in SwiftUI view.
struct UserChoiceView<DecisionView: View>: View {
let subview: DecisionView
var body: some View {
subview
.padding()
.offset(x: 10)
}
}
struct LikeDislikeView_Previews: PreviewProvider {
static var previews: some View {
UserChoiceView(subview: RoundedRectangle(cornerRadius: 10)
.fill(Color.red.opacity(0.9)))
}
}
Code above works fine, but Xcode can't generate preview.
I receive this error:
reference to generic type 'UserChoiceView' requires arguments in <...>
I think I can solve this by using AnyView type erasure, but maybe there are other workarounds.
You need to explicitly define the view in the preview.
struct UserChoiceView<DecisionView: View>: View {
let subview: DecisionView
var body: some View {
/// ...
}
}
struct LikeDislikeView_Previews: PreviewProvider {
static var decisionView: View {
// return SomeDecisionView()
}
static var previews: some View {
UserChoiceView<Self.decisionView>(subview: Self.decisionView)
}
}

SwiftUI can't create navigationview

I'm following through some swiftUI tutorial and I couldn't figure out what this meant.
This was the very first step, and I haven't done anything other than adding the NavigationView. How do I resolve this?
That's just container, you need some content inside, If you are just trying something out try following:
var body: some View {
NavigationView {
Text("Testing")
}
}
You cannot have an empty NavigationView. Add something inside.
struct ContentView: View {
var body: some View {
NavigationView {
Text("Text here")
}
}
}
FIRST: Add new SwiftUI-View (Name: MapView.swift without code-changing )
SECOND: Add new SwiftUI-View (Name: SecondView.swift)
THEN Change ContentView and SecondView:
a) ContentView.swift
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
MapView() // on upper Screen will appear: "Hello World"
NavigationView {
NavigationLink(destination: SecondView()) {
VStack {
Text("click here")
.fontWeight(.heavy)
.font(.largeTitle)
.padding()
Text("go to screen II")
}
}
} //End of NavigationView
}// End of VStack
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
VStack {
ContentView()
}
}
}
b) SecondView.swift
import SwiftUI
struct SecondView: View {
var body: some View {
VStack {
Text("Screen II")
.fontWeight(.heavy)
.foregroundColor(.blue)
.font(.largeTitle)
.padding()
Text("you changed it")
Text("GRATULATION!")
}
}
}
struct SecondView_Previews: PreviewProvider {
static var previews: some View {
SecondView()
}
}
c) MapView.swift
import SwiftUI
struct MapView: View {
var body: some View {
Text(/*#START_MENU_TOKEN#*/"Hello, World!"/*#END_MENU_TOKEN#*/)
}
}
struct MapView_Previews: PreviewProvider {
static var previews: some View {
MapView()
}
}

Creating BaseView class in SwiftUI

Lately started learning/developing apps with SwiftUI and seems pretty easy to build the UI components. However, struggling creating a BaseView in SwiftUI. My idea is to have the common UI controls like background , navigation , etc in BaseView and just subclass other SwiftUI views to have the base components automatically.
Usually you want to either have a common behaviour or a common style.
1) To have a common behaviour: composition with generics
Let's say we need to create a BgView which is a View with a full screen image as background. We want to reuse BgView whenever we want. You can design this situation this way:
struct BgView<Content>: View where Content: View {
private let bgImage = Image.init(systemName: "m.circle.fill")
let content: Content
var body : some View {
ZStack {
bgImage
.resizable()
.opacity(0.2)
content
}
}
}
You can use BgView wherever you need it and you can pass it all the content you want.
//1
struct ContentView: View {
var body: some View {
BgView(content: Text("Hello!"))
}
}
//2
struct ContentView: View {
var body: some View {
BgView(content:
VStack {
Text("Hello!")
Button(action: {
print("Clicked")
}) {
Text("Click me")
}
}
)
}
}
2) To have a common behaviour: composition with #ViewBuilder closures
This is probably the Apple preferred way to do things considering all the SwiftUI APIs. Let's try to design the example above in this different way
struct BgView<Content>: View where Content: View {
private let bgImage = Image.init(systemName: "m.circle.fill")
private let content: Content
public init(#ViewBuilder content: () -> Content) {
self.content = content()
}
var body : some View {
ZStack {
bgImage
.resizable()
.opacity(0.2)
content
}
}
}
struct ContentView: View {
var body: some View {
BgView {
Text("Hello!")
}
}
}
This way you can use BgView the same way you use a VStack or List or whatever.
3) To have a common style: create a view modifier
struct MyButtonStyle: ViewModifier {
func body(content: Content) -> some View {
content
.padding()
.background(Color.red)
.foregroundColor(Color.white)
.font(.largeTitle)
.cornerRadius(10)
.shadow(radius: 3)
}
}
struct ContentView: View {
var body: some View {
VStack(spacing: 20) {
Button(action: {
print("Button1 clicked")
}) {
Text("Button 1")
}
.modifier(MyButtonStyle())
Button(action: {
print("Button2 clicked")
}) {
Text("Button 2")
}
.modifier(MyButtonStyle())
Button(action: {
print("Button3 clicked")
}) {
Text("Button 3")
}
.modifier(MyButtonStyle())
}
}
}
These are just examples but usually you'll find yourself using one of the above design styles to do things.
EDIT: a very useful link about #functionBuilder (and therefore about #ViewBuilder) https://blog.vihan.org/swift-function-builders/
I got a idea about how to create a BaseView in SwiftUI for common usage in other screen
By the way
Step .1 create ViewModifier
struct BaseScene: ViewModifier {
/// Scene Title
var screenTitle: String
func body(content: Content) -> some View {
VStack {
HStack {
Spacer()
Text(screenTitle)
.font(.title)
.foregroundColor(.white)
Spacer()
}.padding()
.background(Color.blue.opacity(0.8))
content
}
}
}
Step .2 Use that ViewModifer in View
struct BaseSceneView: View {
var body: some View {
VStack {
Spacer()
Text("Home screen")
.font(.title)
Spacer()
}
.modifier(BaseScene(screenTitle: "Screen Title"))
}
}
struct BaseSceneView_Previews: PreviewProvider {
static var previews: some View {
Group {
BaseSceneView()
}
}
}
Your Output be like:

How to pass one SwiftUI View as a variable to another View struct

I'm implementing a very custom NavigationLink called MenuItem and would like to reuse it across the project. It's a struct that conforms to View and implements var body : some View which contains a NavigationLink.
I need to somehow store the view that shall be presented by NavigationLink in the body of MenuItem but have yet failed to do so.
I have defined destinationView in MenuItem's body as some View and tried two initializers:
This seemed too easy:
struct MenuItem: View {
private var destinationView: some View
init(destinationView: View) {
self.destinationView = destinationView
}
var body : some View {
// Here I'm passing destinationView to NavigationLink...
}
}
--> Error: Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements.
2nd try:
struct MenuItem: View {
private var destinationView: some View
init<V>(destinationView: V) where V: View {
self.destinationView = destinationView
}
var body : some View {
// Here I'm passing destinationView to NavigationLink...
}
}
--> Error: Cannot assign value of type 'V' to type 'some View'.
Final try:
struct MenuItem: View {
private var destinationView: some View
init<V>(destinationView: V) where V: View {
self.destinationView = destinationView as View
}
var body : some View {
// Here I'm passing destinationView to NavigationLink...
}
}
--> Error: Cannot assign value of type 'View' to type 'some View'.
I hope someone can help me. There must be a way if NavigationLink can accept some View as an argument.
Thanks ;D
To sum up everything I read here and the solution which worked for me:
struct ContainerView<Content: View>: View {
#ViewBuilder var content: Content
var body: some View {
content
}
}
This not only allows you to put simple Views inside, but also, thanks to #ViewBuilder, use if-else and switch-case blocks:
struct SimpleView: View {
var body: some View {
ContainerView {
Text("SimpleView Text")
}
}
}
struct IfElseView: View {
var flag = true
var body: some View {
ContainerView {
if flag {
Text("True text")
} else {
Text("False text")
}
}
}
}
struct SwitchCaseView: View {
var condition = 1
var body: some View {
ContainerView {
switch condition {
case 1:
Text("One")
case 2:
Text("Two")
default:
Text("Default")
}
}
}
}
Bonus:
If you want a greedy container, which will claim all the possible space (in contrary to the container above which claims only the space needed for its subviews) here it is:
struct GreedyContainerView<Content: View>: View {
#ViewBuilder let content: Content
var body: some View {
content
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
If you need an initializer in your view then you can use #ViewBuilder for the parameter too. Even for multiple parameters if you will:
init(#ViewBuilder content: () -> Content) {…}
The way Apple does it is using function builders. There is a predefined one called ViewBuilder. Make it the last argument, or only argument, of your init method for MenuItem, like so:
..., #ViewBuilder builder: #escaping () -> Content)
Assign it to a property defined something like this:
let viewBuilder: () -> Content
Then, where you want to diplay your passed-in views, just call the function like this:
HStack {
viewBuilder()
}
You will be able to use your new view like this:
MenuItem {
Image("myImage")
Text("My Text")
}
This will let you pass up to 10 views and use if conditions etc. though if you want it to be more restrictive you will have to define your own function builder. I haven't done that so you will have to google that.
You should make the generic parameter part of MenuItem:
struct MenuItem<Content: View>: View {
private var destinationView: Content
init(destinationView: Content) {
self.destinationView = destinationView
}
var body : some View {
// ...
}
}
You can create your custom view like this:
struct ENavigationView<Content: View>: View {
let viewBuilder: () -> Content
var body: some View {
NavigationView {
VStack {
viewBuilder()
.navigationBarTitle("My App")
}
}
}
}
struct ENavigationView_Previews: PreviewProvider {
static var previews: some View {
ENavigationView {
Text("Preview")
}
}
}
Using:
struct ContentView: View {
var body: some View {
ENavigationView {
Text("My Text")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
You can pass a NavigationLink (or any other view widget) as a variable to a subview as follows:
import SwiftUI
struct ParentView: View {
var body: some View {
NavigationView{
VStack(spacing: 8){
ChildView(destinationView: Text("View1"), title: "1st")
ChildView(destinationView: Text("View2"), title: "2nd")
ChildView(destinationView: ThirdView(), title: "3rd")
Spacer()
}
.padding(.all)
.navigationBarTitle("NavigationLinks")
}
}
}
struct ChildView<Content: View>: View {
var destinationView: Content
var title: String
init(destinationView: Content, title: String) {
self.destinationView = destinationView
self.title = title
}
var body: some View {
NavigationLink(destination: destinationView){
Text("This item opens the \(title) view").foregroundColor(Color.black)
}
}
}
struct ThirdView: View {
var body: some View {
VStack(spacing: 8){
ChildView(destinationView: Text("View1"), title: "1st")
ChildView(destinationView: Text("View2"), title: "2nd")
ChildView(destinationView: ThirdView(), title: "3rd")
Spacer()
}
.padding(.all)
.navigationBarTitle("NavigationLinks")
}
}
The accepted answer is nice and simple. The syntax got even cleaner with iOS 14 + macOS 11:
struct ContainerView<Content: View>: View {
#ViewBuilder var content: Content
var body: some View {
content
}
}
Then continue to use it like this:
ContainerView{
...
}
I really struggled to make mine work for an extension of View. Full details about how to call it are seen here.
The extension for View (using generics) - remember to import SwiftUI:
extension View {
/// Navigate to a new view.
/// - Parameters:
/// - view: View to navigate to.
/// - binding: Only navigates when this condition is `true`.
func navigate<SomeView: View>(to view: SomeView, when binding: Binding<Bool>) -> some View {
modifier(NavigateModifier(destination: view, binding: binding))
}
}
// MARK: - NavigateModifier
fileprivate struct NavigateModifier<SomeView: View>: ViewModifier {
// MARK: Private properties
fileprivate let destination: SomeView
#Binding fileprivate var binding: Bool
// MARK: - View body
fileprivate func body(content: Content) -> some View {
NavigationView {
ZStack {
content
.navigationBarTitle("")
.navigationBarHidden(true)
NavigationLink(destination: destination
.navigationBarTitle("")
.navigationBarHidden(true),
isActive: $binding) {
EmptyView()
}
}
}
}
}
Alternatively you can use a static function extension. For example, I make a titleBar extension to Text. This makes it very easy to reuse code.
In this case you can pass a #Viewbuilder wrapper with the view closure returning a custom type that conforms to view. For example:
import SwiftUI
extension Text{
static func titleBar<Content:View>(
titleString:String,
#ViewBuilder customIcon: ()-> Content
)->some View {
HStack{
customIcon()
Spacer()
Text(titleString)
.font(.title)
Spacer()
}
}
}
struct Text_Title_swift_Previews: PreviewProvider {
static var previews: some View {
Text.titleBar(titleString: "title",customIcon: {
Image(systemName: "arrowshape.turn.up.backward")
})
.previewLayout(.sizeThatFits)
}
}
If anyone is trying to pass two different views to other view, and can't do it because of this error:
Failed to produce diagnostic for expression; please submit a bug report...
Because we are using <Content: View>, the first view you passed, the view is going to store its type, and expect the second view you are passing be the same type, this way, if you want to pass a Text and an Image, you will not be able to.
The solution is simple, add another content view, and name it differently.
Example:
struct Collapsible<Title: View, Content: View>: View {
#State var title: () -> Title
#State var content: () -> Content
#State private var collapsed: Bool = true
var body: some View {
VStack {
Button(
action: { self.collapsed.toggle() },
label: {
HStack {
self.title()
Spacer()
Image(systemName: self.collapsed ? "chevron.down" : "chevron.up")
}
.padding(.bottom, 1)
.background(Color.white.opacity(0.01))
}
)
.buttonStyle(PlainButtonStyle())
VStack {
self.content()
}
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: collapsed ? 0 : .none)
.clipped()
.animation(.easeOut)
.transition(.slide)
}
}
}
Calling this View:
Collapsible {
Text("Collapsible")
} content: {
ForEach(1..<5) { index in
Text("\(index) test")
}
}
Syntax for 2 Views
struct PopOver<Content, PopView> : View where Content: View, PopView: View {
var isShowing: Bool
#ViewBuilder var content: () -> Content
#ViewBuilder var popover: () -> PopView
var body: some View {
ZStack(alignment: .center) {
self
.content()
.disabled(isShowing)
.blur(radius: isShowing ? 3 : 0)
ZStack {
self.popover()
}
.frame(width: 112, height: 112)
.opacity(isShowing ? 1 : 0)
.disabled(!isShowing)
}
}
}