I have a Button. I want to set custom background color for highlighted state. How can I do it in SwiftUI?
Button(action: signIn) {
Text("Sign In")
}
.padding(.all)
.background(Color.red)
.cornerRadius(16)
.foregroundColor(.white)
.font(Font.body.bold())
Run Code Online (Sandbox Code Playgroud) 点击时列表行的默认颜色为灰色。
我知道如何使用 .listRowBackground 更改背景颜色,但随后它会更改为整个列表。
如何在点击时更改为自定义颜色,以便只有被点击的行保持红色?
import SwiftUI
struct ExampleView: View {
@State private var fruits = ["Apple", "Banana", "Grapes", "Peach"]
var body: some View {
NavigationView {
List {
ForEach(fruits, id: \.self) { fruit in
Text(fruit)
}
.listRowBackground(Color.red)
}
}
}
}
struct ExampleView_Previews: PreviewProvider {
static var previews: some View {
ExampleView()
}
}
Run Code Online (Sandbox Code Playgroud)
SwiftUIList将自动突出显示点击的行,前提是内部有一个 NavigationLink。
由于我使用嵌入在 UIKit 中的 SwiftUI via UIHostingController,我使用 a 处理导航UINavigationController,所以我不想使用NavigationLink.
但是,我需要在点击时突出显示列表行,这在使用时不存在.onTapGesture
我怎样才能做到这一点?
这是一个例子:
List {
Section(header: Text("Section header text")) {
HStack { // A row in the list
Image(systemName: "circle")
VStack(alignment: .leading) {
Text("profile name")
// Sub label
Text("Description")
.foregroundColor(.secondary)
.font(.system(size: 12))
}
Spacer()
}
.contentShape(Rectangle())
.onTapGesture { // Detect tap on the row
Print("Perform action here...")
// THE TAP IS NOT ANIMATED BECAUSE THERE IS NO NAVIGATION LINK HERE.
}
} …Run Code Online (Sandbox Code Playgroud)