我正在使用 SwiftUI 创建一个小部件,我正在努力解决在 Swift 中非常简单明了的东西。
我有 2 个彼此相邻的图像,我希望它们具有完全相同的大小和纵横比填充,但不会超出范围。
目前它的工作原理是我有一个图像和文本的视图。然后是一个父视图,它有一个 HStack 和其中 2 个视图。
基本上我想要实现的是这个视图,但图像正确:
这是这样做的:
VStack() {
Image(uiImage: image)
.resizable()
Text(affirmation.title)
.font(.body)
.foregroundColor(Color(UIColor.MAPurple()))
}
}
对于父视图:
HStack {
Spacer()
CardView(text: text, image: firstImage)
Spacer()
CardView(text: text, image: secondImage)
Spacer()
}
如果我像在 Swift 中那样添加纵横比来填充,它的外观是这样的:
更新
添加一个最小的可重现示例:
struct CardView: View {
let text: String
let image: UIImage
var body: some View {
VStack(alignment: .leading) {
Image(uiImage: image)
.resizable()
// .aspectRatio(contentMode: .fill)
.clipped()
Text(text)
.font(.body)
.multilineTextAlignment(.leading)
.foregroundColor(Color.blue)
}
}
}
struct ParentView: View {
let firstText: String = "This is something"
let firstImage: UIImage
let secondText: String = "This is something else"
let secondImage: UIImage
let top: String = "This is the top string"
var body: some View {
VStack {
Spacer()
Spacer()
Text(top)
.font(.largeTitle)
.foregroundColor(Color(UIColor.MAPurple()))
.padding(.all, 10)
.minimumScaleFactor(0.4)
Spacer()
Spacer()
HStack {
Spacer()
CardView(text: firstText, image: firstImage)
Spacer()
CardView(text: secondText, image: secondImage)
Spacer()
}
Spacer()
Spacer()
}
.background(Color.yellow)
.edgesIgnoringSafeArea(.all)
}
}