繁体   English   中英

如何在 SwiftUI 中创建 UIView 的视觉等效项?

[英]How would I create the visual equivalent of a UIView in SwiftUI?

这是我的项目中使用 SwiftUI 的List项的代码。

struct ServicesListItem: View {

    var title: String
    var description: String
    var colorHex: String
    var imageName: String

    var body: some View {
        HStack {
            Image(imageName)
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width: 50, height: 50)
            VStack(alignment: .leading, spacing: 4) {

                Text(title)
                    .font(.system(size: 14, weight: .black, design: .rounded))
                    .foregroundColor(Color(hex: colorHex))

                Text(description)
                    .font(.system(size: 10, weight: .medium, design: .rounded))
                    .foregroundColor(Color.gray)
            }
            .frame(height: 60)
        }
    }
}

我想将每个ServicesListItem的所有元素放在另一个“视图”中,并在所有侧面添加填充,以使每个项目的内容看起来都在凸起的视图中,而不是List的边缘到边缘的外观。 我通过使用 UIView 作为 UITableViewCell 内的父视图,使用 UIKit 轻松完成了此操作。 尚未找到使用 SwiftUI 执行此操作的方法。 可能吗?

SwiftUI 1.0

嗨 Austin,以下是我对您的列表项视图所做的一些相关更改:

  • 将框架移动到 HStack 级别
  • 使用.maxWidth: .infinity使 HStack 填充设备的宽度
  • 添加了纯色背景颜色,然后您可以为“凸起的外观”添加阴影

代码

struct ServicesListItem: View {
    var title: String
    var description: String
    var colorHex: String
    var imageName: String

    var body: some View {
        HStack {
            Image(imageName)
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width: 50, height: 50)

            VStack(alignment: .leading, spacing: 4) {
                Text(title)
                    .font(.system(size: 14, weight: .black, design: .rounded))
                    .foregroundColor(Color(hex: colorHex))

                Text(description)
                    .font(.system(size: 10, weight: .medium, design: .rounded))
                    .foregroundColor(Color.gray)
            }
        }
        // Set the size of entire row. maxWidth makes it take up whole width of device.
        .frame(maxWidth: .infinity, maxHeight: 60, alignment: .leading)
        .padding(10) // Spacing around all the contents
        // Add a solid colored background that you can put a shadow on
        // (corner radius optional)
        .background(Color.white.cornerRadius(5).shadow(radius: 3))
    }
}

例子

截图示例

这和你想的一样吗?

(从 SwiftUI 1.0 开始,我们不知道如何删除这些线条。☹️)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM