我的目标是使用三元运算符为我的图像添加阴影,但如果视图使用默认图像,则不添加阴影。
这是我的代码:
import SwiftUI
struct ImageDisplay: View {
@State private var defaultImage: Image = Image(systemName: "person.crop.circle.fill")
private var defaultText: String = "Add picture"
private var hasShadow: Bool = true
private var text: String?
private var image: Binding<Image>?
public init(_ text: String, image: Binding<Image>) {
self.init(
text: .some(text),
image: image
)
}
public init(image: Binding<Image>) {
self.init(
text: nil,
image: image
)
}
public init() {
self.init(
text: nil,
image: nil
)
}
private init(text: String?, image: Binding<Image>?) {
self.text = text
self.image = image
}
private struct InternalImageDisplay: View {
var text: String
var hasShadow: Bool /// NOT CERTAIN WHERE THIS BELONGS, OR IF IT GOES HERE ...
@Binding var image: Image
@ViewBuilder
var body: some View {
VStack {
image
.imageDisplayStyle()
.shadow(radius: hasShadow ? 4.0 : 0.0) /// HERE IS WHERE I'LL USE IT...
Button(action: {
//TODO: - Code to present image picker.
}, label: {
Text(text)
})
}
}
}
var body: some View {
InternalImageDisplay(
text: text ?? defaultText,
hasShadow: false, /// THIS IS NOT WORKING IN ANY IMPLEMENTATION ...
image: image ?? $defaultImage
)
}
}
我也有这个扩展Image
:
import SwiftUI
extension Image {
func imageDisplayStyle() -> some View {
return self
.resizable()
.scaledToFill()
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
.aspectRatio(contentMode: .fit)
.clipShape(Circle())
.foregroundColor(.gray)
}
}
我正在尝试使看起来像这样的代码可以很好地工作并且很棒,除了影子布尔:
struct ContentView: View {
@State private var image = Image("img1")
@State private var defaultImage: Bool = true
var body: some View {
VStack (spacing: 48) {
// no binding
ImageDisplay()
// binding
ImageDisplay("Select image", image: $image)
ImageDisplay(image: $image)
}
.frame(width: 190)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}