所以我正在構建我的第一個應用程式,我試圖在按鈕下方獲取一些文本,但它仍然應該是按鈕的一部分。所以這就是我得到的:
`Button{
print("tapped")
} label: {
Image("Wand")
.resizable()
.frame(width: 100, height: 100)
}
.font(.title3)
.background(Color.gray)
.foregroundColor(.black)
.cornerRadius(20)`
這看起來像這樣: 按鈕
但我想要這樣: Button2
我試過將“VStack”放入標簽,但文本保留在灰色按鈕中
uj5u.com熱心網友回復:
我認為它可以幫助你
public struct VerticalLabelStyle: LabelStyle {
public let spacing: CGFloat
public init(spacing: CGFloat = 8) {
self.spacing = spacing
}
public func makeBody(configuration: Configuration) -> some View {
VStack(alignment: .center, spacing: spacing) {
configuration.icon
configuration.title
}
}
}
public struct ContentView: View {
@State private var text: String = ""
public var body: some View {
Label {
Text(text)
} icon: {
Image(systemName: "gamecontroller.fill")
.resizable()
.frame(width: 44, height: 44, alignment: .center)
}
.frame(width: 100, height: 100)
.labelStyle(VerticalLabelStyle())
.onTapGesture(perform: onTap)
}
func onTap() {
text = "tapped"
}
}
如果您有一些問題,請提問
uj5u.com熱心網友回復:
你對 VStack 的想法是正確的方法。您只需要記住放置修改器的位置。在您的情況下,您將它們放在按鈕級別。這意味著它們應用于整個標簽,這就是您的文本位于灰色背景內的原因。只需更新 VStack 中修改器的位置。這是一個簡短的例子:
Button {
// Your button action
} label: {
VStack {
RoundedRectangle(cornerRadius: 25)
.frame(width: 100, height: 100)
.padding()
.background(Color.black) // new position of background modifier that is only applied on your Image (here a rectangle)
Text("Foo")
.font(.title3)
.foregroundColor(.black)
// These modifiers could stay on button level, but I moved them here to explicitly show where they applied
}
}
請記住,您可以將任何視圖放在按鈕的標簽內,在這種情況下,文本是按鈕的一部分,如果用戶點擊它,它將觸發操作。如果您只希望影像是點擊動作,請將您的按鈕包裹在一個 VStack 中,該 VStack 僅包含影像和文本作為堆疊的第二部分,如下所示:
VStack {
Button {
// Your button action
} label: {
VStack {
RoundedRectangle(cornerRadius: 25)
.frame(width: 100, height: 100)
.padding()
.background(Color.black)
}
}
Text("Foo")
.font(.title3)
.foregroundColor(.black)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/340963.html
