An extension to the View
protocol that provides conditional view modifiers.
ViewCondition
enhances SwiftUI's conditional rendering capabilities, makes it easier for developers to create adaptive and responsive user interfaces. With ViewCondition
, you can easily apply modifiers, control visibility, or hide views based on various conditions such as boolean logic, operating system, or module availability. This flexibility allows you to tailor your app's interface for different platforms and user needs without complex conditional statements.
You can find the documentation here: https://kevinhermawan.github.io/ViewCondition/documentation/viewcondition
You can add ViewCondition
as a dependency to your project using Swift Package Manager by adding it to the dependencies value of your Package.swift
.
dependencies: [
.package(url: "https://github.com/kevinhermawan/ViewCondition.git", .upToNextMajor(from: "2.0.0"))
]
Alternatively, in Xcode:
- Open your project in Xcode.
- Click on
File
->Swift Packages
->Add Package Dependency...
- Enter the repository URL:
https://github.com/kevinhermawan/ViewCondition.git
- Choose the version you want to add. You probably want to add the latest version.
- Click
Add Package
.
The if
modifiers allow you to conditionally apply modifications to a view.
Text("Hello, World!")
.if(someCondition) { view in
view.foregroundColor(.red)
}
Text("Hello, World!")
.if(os: .iOS) { view in
view.padding()
}
Text("Hello, World!")
.if(canImport: .uiKit) { view in
view.foregroundColor(.blue)
}
Text("Hello, World!")
.if([condition1, condition2, condition3]) { view in
view.bold()
}
Text("Hello, World!")
.if(os: [.iOS, .macOS]) { view in
view.font(.largeTitle)
}
Text("Hello, World!")
.if(canImport: [.uiKit, .appKit]) { view in
view.italic()
}
The visible
modifiers control the visibility of a view.
Text("I'm visible!")
.visible(if: someCondition)
Text("I might be removed")
.visible(if: someCondition, removeCompletely: true)
Text("iOS Only")
.visible(on: .iOS)
Text("UIKit Available")
.visible(ifCanImport: .uiKit)
Text("All conditions must be true")
.visible(if: [condition1, condition2, condition3])
Text("iOS or macOS")
.visible(on: [.iOS, .macOS])
Text("UIKit or AppKit")
.visible(ifCanImport: [.uiKit, .appKit])
The hide
modifiers control the hiding of a view.
Text("I'm hidden!")
.hide(if: someCondition)
Text("I might be removed")
.hide(if: someCondition, removeCompletely: true)
Text("Hidden on iOS")
.hide(on: .iOS)
Text("Hidden if UIKit is available")
.hide(ifCanImport: .uiKit)
Text("Hidden if all conditions are true")
.hide(if: [condition1, condition2, condition3])
Text("Hidden on iOS or macOS")
.hide(on: [.iOS, .macOS])
Text("Hidden if UIKit or AppKit is available")
.hide(ifCanImport: [.uiKit, .appKit])