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

Aus*_*nyi 4 list ios swift swiftui

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

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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ens 5

SwiftUI 1.0

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

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

代码

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))
    }
}
Run Code Online (Sandbox Code Playgroud)

例子

截图示例

这和你想的一样吗?

(从 SwiftUI 1.0 开始,我们不知道如何删除这些行。??)