Currently, i have made a custom view in SwiftUI containing an Image with some details. How can we add specific image modifiers outside my view instance?
import Foundation
import SwiftUI
import Combine
struct RemoteImage: View {
// Hold reference to our remote resource through binding
@ObjectBinding
private var resource: RemoteResource
// Initialize the Image with a string
init(urlString: String) {
// Create our resource and request our data
// Will fetch the resource from the internet
self.resource = RemoteResource(urlString)
}
// Computed var that will return a placeholder image our our actual resource
private var image: UIImage {
self.resource.data.flatMap(UIImage.init) ?? UIImage(named: "placeholder")!
}
var body: some View {
Image(uiImage: image)
}
}
How would i add modifiers from an instance of RemoteImage
to Image
RemoteImage(urlString: "image-url-here")
.resizable()
.scaledToFit()
If anyone would know a solution to my problem please let me know.
To create a custom modifier, create a new struct that conforms to the ViewModifier protocol. This has only one requirement, which is a method called body that accepts whatever content it's being given to work with, and must return some View .
A modifier that you apply to a view or another view modifier, producing a different version of the original value.
To display an image, simply add the image file into your asset library (Assets. xcassets) and then pass the name of the asset as a string to your Image element in Line 1.
Use a group to collect multiple views into a single instance, without affecting the layout of those views, like an HStack , VStack , or Section would. After creating a group, any modifier you apply to the group affects all of that group's members.
If you declare your RemoteImage like this:
import Foundation
import SwiftUI
import Combine
struct RemoteImage: View {
// Hold reference to our remote resource through binding
@ObservedObject
private var resource: RemoteResource
// Initialize the Image with a string
init(urlString: String) {
// Create our resource and request our data
// Will fetch the resource from the internet
self.resource = RemoteResource(urlString)
}
// Computed var that will return a placeholder image our our actual resource
private var image: UIImage {
self.resource.data.flatMap(UIImage.init) ?? UIImage(named: "placeholder")!
}
var body: Image {
Image(uiImage: image)
}
}
then you can call all Image specific modifiers like this:
RemoteImage(urlString: "image-url-here").body
.resizable()
.scaledToFit()
Not ideal, but at least you don't have to redeclare every single modifier manually.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With