gpt4 book ai didi

ios - 有没有办法使用 Geometry Reader 将我的 SwiftUI 图像的宽度定义为相对于屏幕尺寸?

转载 作者:行者123 更新时间:2023-12-01 16:11:53 26 4
gpt4 key购买 nike

我正在通过一个示例应用程序来熟悉 Swift 和 SwiftUI,并且我想结合使用自定义 View 和 GeometryReader 的复合布局的想法来确定设备的屏幕大小。

我正在尝试构建的页面是一个可滚动的 friend 列表,其中每一行项目都是一个按钮,可以选择该按钮来展开列表以查看每个 friend 的更多详细信息。我已将按钮和所有包含 View 构建为 FriendView在我的内部使用 FriendListView .我已经定义了 2 GeometryReader FriendListView 内的意见但不知道如何从 FriendView 中定义每行的大小使其保持适当的大小。

之所以需要这样做,是因为并非用户稍后可以为他们的 friend 设置的每个图像都具有相同的尺寸,因此我希望保持一致。我知道我可以设置一个 .frame()修改器和硬编码宽度,但我希望它与屏幕相关,以便在所有手机屏幕上保持一致。

示例:当一行未展开时,图像应占设备宽度的一半。当它展开时,我希望它占据设备屏幕宽度的四分之一。

截图

Application View

示例代码

struct FriendListView: View {
var pets = ["Woofer", "Floofer", "Booper"]

var body: some View {
GeometryReader { geo1 in
NavigationView {
GeometryReader { geo2 in
List(self.pets, id: \.self) { pet in
FriendView(name: pet)

}// End of List
}
.navigationBarTitle(Text("Furiends"))

}// End of NavigationView
}// End of GeometryReader geo1
}// End of body
}
struct FriendView: View {
@State private var isExpanded = false
var randomPic = Int.random(in: 1...2)

var name = ""
var breed = "Dawg"
var body: some View {

Button(action: self.toggleExpand) {
HStack {
VStack {
Image("dog\(self.randomPic)")
.resizable()
.renderingMode(.original)
.scaledToFill()
.clipShape(Circle())

if self.isExpanded == false {
Text(self.name)
.font(.title)
.foregroundColor(.primary)
}
}

if self.isExpanded == true {
VStack {
Text(self.name).font(.title)
Text(self.breed).font(.headline)
}
.foregroundColor(.primary)
}
}
}// End of Button
}
func toggleExpand() {
isExpanded.toggle()
}
}

最佳答案

您可以定义一个 GeometryReader在顶级FriendListView并将屏幕宽度传递给 FriendView :

struct FriendListView: View {
var pets = ["Woofer", "Floofer", "Booper"]

var body: some View {
GeometryReader { geo in
NavigationView {
List(self.pets, id: \.self) { pet in
FriendView(name: pet, screenWidth: geo.size.width)
}
.navigationBarTitle(Text("Furiends"))
}
}
}
}

然后使用 .frame设置图像的最大宽度。
struct FriendView: View {
...

var screenWidth: CGFloat

var imageWidth: CGFloat {
isExpanded ? screenWidth / 4 : screenWidth / 2
}

var body: some View {
Button(action: self.toggleExpand) {
HStack {
VStack {
Image("dog\(self.randomPic)")
.resizable()
.renderingMode(.original)
.scaledToFill()
.clipShape(Circle())
.frame(width: imageWidth, height: imageWidth) // <- add frame boundaries

if self.isExpanded == false {
Text(self.name)
.font(.title)
.foregroundColor(.primary)
}
}

if self.isExpanded == true {
VStack {
Text(self.name).font(.title)
Text(self.breed).font(.headline)
}
.foregroundColor(.primary)
}
}
}
}

func toggleExpand() {
isExpanded.toggle()
}
}

如果您希望图片居中,您可以使用 Spacer :
HStack {
Spacer()
FriendView(name: pet, screenWidth: geo.size.width)
Spacer()
}

关于ios - 有没有办法使用 Geometry Reader 将我的 SwiftUI 图像的宽度定义为相对于屏幕尺寸?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62361192/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com