【问题标题】:How would I create the visual equivalent of a UIView in SwiftUI?如何在 SwiftUI 中创建 UIView 的视觉等效项?
【发布时间】:2020-01-22 20:12:52
【问题描述】:

这是我使用 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 执行此操作的方法。有可能吗?

【问题讨论】:

    标签: ios swift list swiftui


    【解决方案1】:

    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 开始,我们不知道如何删除这些线条。☹️)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-14
      • 1970-01-01
      • 1970-01-01
      • 2010-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多