[英]How to create macOS Big Sur-style Search Box with exterior focus ring in SwiftUI?
[英]SwiftUI custom TextField with focus ring on macOS
我想在 macOS 上使用我的自定義 TextField 樣式,它也有焦點環
但是我遇到了 2 個問題,具體取決於我使用.textFieldStyle(.roundedBorder)
還是.textFieldStyle(.plain)
struct FTextFieldStyle: TextFieldStyle {
func _body(configuration: TextField<Self._Label>) -> some View {
configuration
.textFieldStyle(.roundedBorder)
.frame(maxWidth: .infinity)
.padding(6)
.foregroundColor(Color.black)
.background(Color.white)
.cornerRadius(6)
.shadow(color: .black.opacity(0.25), radius: 2, x: 0, y: 0.5)
.focusable()
}
}
TextField("E-mail", text: $email).textFieldStyle(FTextFieldStyle())
對焦環錯位
“擋板”無法移除
那么如何擁有一個具有系統焦點環的自定義 TextField 呢?
您可以使用@FocusState
& .overlay
創建自定義焦點環:
struct FTextFieldStyle: TextFieldStyle {
@FocusState var isFocused: Bool
func _body(configuration: TextField<Self._Label>) -> some View {
configuration
.textFieldStyle(.plain)
.frame(maxWidth: .infinity)
.padding(6)
.foregroundColor(Color.black)
.background(Color.white)
.cornerRadius(6)
.shadow(color: .black.opacity(0.25), radius: 2, x: 0, y: 0.5)
.focusable()
.focused($isFocused)
.overlay(RoundedRectangle(cornerRadius: 6).stroke(Color.accentColor.opacity(0.5), lineWidth: 4).opacity(isFocused ? 1 : 0).scaleEffect(isFocused ? 1 : 1.04))
.animation(isFocused ? .easeIn(duration: 0.2) : .easeOut(duration: 0.0), value: isFocused)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.