簡體   English   中英

SwiftUI 自定義 TextField 與 macOS 上的焦點環

[英]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())

使用 .roundedBorder 時

  1. 對焦環錯位

  2. “擋板”無法移除

在此處輸入圖像描述

使用 .plain 時

  • 我無法恢復對焦環功能,即使添加了 .focusable(),對焦環也不見了

在此處輸入圖像描述

那么如何擁有一個具有系統焦點環的自定義 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM