struct MostViewedViewItem: View {
    let moviePic: String = "image_placeholder"
    let movieName: String = "Movie Name Loading..."
    
    var body: some View {
        Button {
            // TODO: add a navigation link to the movie
        } label: {
            ZStack(alignment: .bottom) {
                Image(moviePic)
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .frame(width: 170, height: 100)
                    .clipShape(RoundedRectangle(cornerRadius: 3))
                    .overlay(
                        Text(movieName)
                            .scaledToFill()
                            .frame(height: 30)
                            .foregroundColor(.white)
                            .background (
                                Rectangle()
                                    .fill(Color("lighter_bg"))
                                    .opacity(0.4)
                            ),
                        alignment: .bottom
                    )
            }
        }
    }
}

enter image description here

我试图在背景中添加填充,所以我希望背景填充整个水平空间,但我希望文本有一些填充,如何做到这一点?

推荐答案

你应该把paddingbefore相加到.background.此外,您可能希望使用scaledToFillframe instead,如下所示:

Text(movieName)
    .frame(maxWidth: .infinity)
    .foregroundColor(.white)
    .padding()
    .background(Color("lighter_bg").opacity(0.4))

Here is another answer了解如何更好地演示如何应用填充

Ios相关问答推荐

在SwiftData中从@ Query创建可排序、有序和分组的数据

第三方框架的iOS隐私声明

如何在SWIFT中处理不可发送的类型?

React Native IOS base64 编码图像不显示

从 PHAssets 生成图像时,iOS 应用程序因内存问题而崩溃

如何根据条件快速将返回类型设为 LinearGradient 或 AngularGradient?

如何在 SwiftUI 中将选项卡放在滚动视图中?

小部件链接有效,但不执行任何操作

在 SwiftUI 中将 TextEditor 文本计数连接到 ProgressView

如何为视图的 colored颜色 和宽度设置动画?

如何在 Swift 上的 sendSynchronousRequest 中判断 Response.statusCode

iPhone 6 和 6 Plus 媒体查询

UIButton在iOS7中没有显示突出显示

如何忽略touch 事件并将它们传递给另一个子视图的 UIControl 对象?

在 Swift 中追加字符串

在 iOS 上存储身份验证令牌 - NSUserDefaults 与 keys 串?

SLComposeViewController 分享教程

iPhone:什么是 WWDR 中级证书?

在转发类对象中找不到属性

两个数字之间的动画UILabel文本?