I have written a custom view modifier:
import SwiftUI
public struct Watermark: ViewModifier {
// watermark text
public var text: String = " watermark"
public var align: Alignment = .bottomTrailing
// body
public func body(content: Content) -> some View {
let textView = Text(text)
.font(.caption)
.foregroundColor(.white)
.padding(8)
.background(Color.black).padding(5)
.opacity(0.6)
return content.overlay(textView, alignment: align)
}
}
extension View {
// use view modifier
public func watermark(
_ text : String = " watermark",
_ align: Alignment = .bottomTrailing
) -> some View {
self.modifier(Watermark(text: text, align: align))
}
}
and a View
extension:
import SwiftUI
extension View {
// modify the view directly
public func watermark2(
_ text : String = " watermark",
_ align: Alignment = .bottomTrailing
) -> some View
{
let textView = Text(text)
.font(.caption)
.foregroundColor(.white)
.padding(8)
.background(Color.black).padding(5)
.opacity(0.6)
return self.overlay(textView, alignment: align)
}
}
and the following code uses the view modifier and the View
extension above:
import SwiftUI
import PlaygroundSupport
// content view
struct ContentView: View {
var body: some View {
VStack {
// use view modifier
Color.gray.watermark()
Color.gray.watermark("hello", .topTrailing)
// use view extension
Color.gray.watermark2("hi", .center)
Color.gray.watermark2("example", .topLeading)
}
}
}
PlaygroundPage.current.setLiveView(ContentView())
the result looks like this:
My question is: if we can do the job by simply using a View
extension, why bother using a view modifier? What's the benefit of using it?