swift - 如何在 SwiftUI 中访问父框架
问题描述
仍在使用 SwiftUI,但我遇到了问题。我创建了一个带有动态框架的图像,我想要一个标签,它需要是图像的一半宽度(例如图像宽度 = 300;标签宽度 150)
在 UIKit 中,我应该编写如下代码:
Label.widthAnchor.constraint(image.widthAnchor, multiplier: 1/2).isActive = true
我在 SwiftUI 中尝试了类似的东西:
Image(systemName: "j.circle.fill")
.resizable()
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width)
Text("Placeholder").frame(width: Image.frame.width/2, height: 30)
但这不起作用。
我该怎么办?
解决方案
为什么不为两者设置硬尺寸:
Image(systemName: "j.circle.fill")
.resizable()
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width)
Text("Placeholder")
.frame(width: UIScreen.main.bounds.width/2, height: 30)
如果您想在一个地方更改组件的整个大小,您可以这样做:
struct MyView : View {
private var compWidth: CGFloat { UIScreen.main.bounds.width }
var body: some View {
VStack {
Image(systemName: "j.circle.fill")
.resizable()
.frame(width: compWidth, height: compWidth)
Text("Placeholder")
.frame(width: compWidth/2, height: 30)
}
}
}
或者,对于更优雅的方法,您可以查看 GeometryReader
.
推荐阅读
- c# - 如何在 ASP.NET Core WebAssembly .NET 5 中覆盖 Blazor Identity Server 4 中的 LoginDisplay?
- markdown - 在 Markdown 中用不同的对齐方式写一行
- r - 如何纠正无法生成 ggplot2 图表的错误?
- npm - NPM 发布步骤 AzureDevOps 中的构建错误:[object Object] 不是 PostCSS 插件
- dolphindb - 如何获取 DolphinDB 中分布式表的磁盘使用情况?
- javascript - 为什么我不能从另一个方法访问我在 main 方法中创建的 int 数组值?(初级 Java 编码器)
- maven - Apache Archiva 失败/损坏:错误 org.apache.jackrabbit.core.ItemManager [] - 未能检索项目的项目状态
- javascript - Javascript选择同一类的多个图像
- deployment - Bitrise 构建失败“无法提交编辑,错误:googleapi:得到 HTTP 响应代码 502,正文:”
- python - 为什么我的 HTTP Post 在烧瓶中不起作用?