在watchOS中使用.listRowBackground时如何将cornerRadius添加到SwiftUI List Cell?
Posted
技术标签:
【中文标题】在watchOS中使用.listRowBackground时如何将cornerRadius添加到SwiftUI List Cell?【英文标题】:How to add cornerRadius to SwiftUI List Cell when using .listRowBackground in watchOS? 【发布时间】:2019-10-07 12:05:29 【问题描述】:我试图在手表上获得正常的List
,每个单元格上都有一个listRowBackground
图像。
但是当我将图像设置为listRowBackground
时,标准List
的角半径消失(见下文)。
我尝试在 Cell-View
本身中设置修改的background
,但这会导致同样的问题。
查看 Visual View Debugger,背景图像似乎远远超出了单元格本身。
struct ListView: View
@ObservedObject var model: ListModel
var body: some View
List
ForEach(self.model.items) item in
NavigationLink(destination: PlayerView(item: item))
ListCell(item: item).frame(height: 100)
.listRowBackground(Image(uiImage: item.image)
.resizable()
.scaledToFill()
.opacity(0.7)
)
.listStyle(CarouselListStyle())
.navigationBarTitle(Text("Today"))
@available(watchOSApplicationExtension 6.0, *)
struct ListCell: View
var item: ListItem
var body: some View
VStack(alignment: .leading)
Text("\(self.item.length) MIN . \(self.item.category)")
.font(.system(.caption, design: .default))
.foregroundColor(.green)
.padding(.horizontal)
.padding(.top, 2)
Text(self.item.title)
.font(.headline)
.lineLimit(2)
.padding(.horizontal)
图片:带背景图片:
图片:无背景图片:
【问题讨论】:
您是否尝试将图像添加到 ListCell 而不是 ListRowBackground?可以使用 ZStack 完成,因此文本位于其之上。我还没有在手表上使用它,但是在 ios 中,ListRowBackground 从一侧覆盖到另一侧,“单元格”位于其顶部。 问题在于将其调整到正确的大小。但结合.buttonStyle(PlainButtonStyle())
这可能有效。谢谢!
【参考方案1】:
这适用于我Xcode 11.5,只需添加.clipped()
和.cornerRadius(10)
修饰符。
List
Text("Sample cell text")
.listRowBackground(
Color(.blue)
.clipped()
.cornerRadius(10))
【讨论】:
请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助、质量更好,并且更有可能吸引投票。【参考方案2】:您是否尝试将clipped()
添加到NavigationLink
?
【讨论】:
【参考方案3】:我想通了!
我将图像包裹在GeometryReader
中,并将clipped()
和cornerRadius(10)
添加到GeometryReader
。
并将buttonStyle(PlainButtonStyle())
添加到NavigationLink
。
private func backgroundImage() -> some View
return GeometryReader g in
Image(<image>)
.resizable()
.blur(radius: 2)
.scaledToFill()
.frame(width: g.size.width, height: g.size.height)
.clipped()
.cornerRadius(10)
然后将.listRowBackground(self.backgroundImage())
添加到NavigationLink
。
【讨论】:
以上是关于在watchOS中使用.listRowBackground时如何将cornerRadius添加到SwiftUI List Cell?的主要内容,如果未能解决你的问题,请参考以下文章
watchOS 3 在设备和手表之间共享的类中使用 WCSession
WatchOS 在条件视图中使用 ObservableObject 导致运行时错误