- 看了下源码 ViewModifier 是一个 protocol
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol ViewModifier {
/// The type of view representing the body.
associatedtype Body : View
/// Gets the current body of the caller. 获取调用方的当前主体
///
/// `content` is a proxy for the view that will have the modifier
/// content是具有修饰符的视图的代理
/// represented by `Self` applied to it.
func body(content: Self.Content) -> Self.Body
/// The content view type passed to `body()`.
typealias Content
}
- 新建一个struct实现一下 body方法, 其他的默认就行, 这个方法入参数是当前调用者的主体, 返回值是一个View(协议), 那么是不是入参也应该是一个实现了协议View的对象, 简单理解为UIView
struct Loading: ViewModifier {
func body(content: Content) -> some View {
ZStack(){
content.zIndex(0)
Text("123").zIndex(1)
}
}
}
-
既然可以拿到uiview 我们就可以做很多事情了, 像上面一样调整布局, 对content进行一些属性设置等等, 看你的需求了
-
自定义了 ViewModifier 使用
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension View {
/// Applies a modifier to a view and returns a new view.
///
/// Use this modifier to combine a ``View`` and a ``ViewModifier``, to
/// create a new view. For example, if you create a view modifier for
/// a new kind of caption with blue text surrounded by a rounded rectangle:
///
/// struct BorderedCaption: ViewModifier {
/// func body(content: Content) -> some View {
/// content
/// .font(.caption2)
/// .padding(10)
/// .overlay(
/// RoundedRectangle(cornerRadius: 15)
/// .stroke(lineWidth: 1)
/// )
/// .foregroundColor(Color.blue)
/// }
/// }
///
/// You can use ``modifier(_:)`` to extend ``View`` to create new modifier
/// for applying the `BorderedCaption` defined above:
///
/// extension View {
/// func borderedCaption() -> some View {
/// modifier(BorderedCaption())
/// }
/// }
///
/// Then you can apply the bordered caption to any view:
///
/// Image(systemName: "bus")
/// .resizable()
/// .frame(width:50, height:50)
/// Text("Downtown Bus")
/// .borderedCaption()
///
/// ![A screenshot showing the image of a bus with a caption reading
/// Downtown Bus. A view extension, using custom a modifier, renders the
/// caption in blue text surrounded by a rounded
/// rectangle.](SwiftUI-View-ViewModifier.png)
///
/// - Parameter modifier: The modifier to apply to this view.
@inlinable public func modifier<T>(_ modifier: T) -> ModifiedContent<Self, T>
}
-
通过 modifier方法即可
-
所以还是要多看源码啊
网友评论