bibin-jaimon / InterviewKit-iOS

5 stars 0 forks source link

How to add a custom ViewModifier in SwiftUI #27

Open bibin-jaimon opened 1 month ago

bibin-jaimon commented 1 month ago

useMaxFrame()

struct MaxFrameModifier: ViewModifier {

    let alignment: Alignment

    init(alignment: Alignment = .top) {
        self.alignment = alignment
    }

    func body(content: Content) -> some View {
        content
            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: alignment)
    }
}

extension View {
    @ViewBuilder
    func useMaxFrame() -> some View {
        self.modifier(MaxFrameModifier())
    }
}

Usage of useMaxFrame()

VStack {
    Text("Hello useMaxFrame")
}
.modifier(MaxFrameModifier())
VStack {
    Text("Hello useMaxFrame")
}
.useMaxFrame()
vinaykumar0339 commented 1 month ago

@bibin-jaimon we can add a property to useMaxFrame modifier to customize the usage of alignment propery by modifying the extension of the view

extension View {
    @ViewBuilder
    func useMaxFrame(alignment: Alignment = .top) -> some View {
        self.modifier(MaxFrameModifier(alignment: alignment))
    }
}

usages

VStack {
    Text("Hello useMaxFrame")
}
.useMaxFrame()

VStack {
    Text("Hello useMaxFrame")
}
.useMaxFrame(alignment: .bottom)