AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79107343
Accepted
sinaar
sinaar
Asked: 2024-10-20 22:47:13 +0800 CST2024-10-20 22:47:13 +0800 CST 2024-10-20 22:47:13 +0800 CST

对于不同的标签,Trim 无法正常工作,并且在 TextField 中键入内容时 FocusState 会重置

  • 772

我正在制作一个 TextField,在输入时,它有一个浮动标签,该标签会切入 TextField 的边框。对于不同的占位符,修剪功能无法按预期工作,例如,如果修剪功能对占位符“名称”正常工作,则对占位符“输入名称”不起作用。此外,第一次在字段中输入时,FocusState 会更改为 false。为什么会发生这种情况?有人可以帮忙修复这些问题吗?

视图代码:

struct RoundedTextField: View {
    @Binding var text: String
    let placeholder: String
    
    init(_ placeholder: String, text: Binding<String>) {
        self.placeholder = placeholder
        self._text = text
    }
    
    @State private var width: CGFloat = .zero
    @State private var labelWidth: CGFloat = .zero
    
    @FocusState private var isFieldFocused
    
    var body: some View {
        ZStack(alignment: .leading) {
            Text(placeholder)
                .foregroundStyle(text.isEmpty ? Color(.placeholderText) : .caribe)
                .padding(.horizontal, 25)
                .offset(y: text.isEmpty ? 0 : -37)
                .scaleEffect(text.isEmpty ? 1 : 0.8, anchor: .leading)
                .overlay {
                    GeometryReader { proxy in
                        Color.clear
                            .onChange(of: text) { _, _ in
                                labelWidth = proxy.size.width
                            }
                    }
                }
            
            TextField("", text: $text)
                .textFieldStyle(RoundedTextFieldStyle(isFieldFocused: isFieldFocused, textIsEmpty: text.isEmpty, width: width, labelWidth: labelWidth))
                .focused($isFieldFocused)
                .overlay {
                    GeometryReader { proxy in
                        Color.clear
                            .onChange(of: text) { _, _ in
                                width = proxy.size.width * (text.isEmpty ? 1 : 0.8)
                            }
                    }
                }
        }
        .animation(.default, value: text)
        .padding()
    }
}

struct RoundedTextFieldStyle: TextFieldStyle {
    var isFieldFocused: Bool
    var textIsEmpty: Bool
    var width: CGFloat
    var labelWidth: CGFloat
    func _body(configuration: TextField<Self._Label>) -> some View {
        configuration
            .padding(.vertical)
            .padding(.horizontal, 25)
            .frame(height: 60)
            .if(textIsEmpty) { view in
                view.background {
                    RoundedRectangle(cornerRadius: 10)
                            .stroke(isFieldFocused ? .caribe : .gray, lineWidth: isFieldFocused ? 2 : 1)
                }
            }
            .if(!textIsEmpty) { view in
                view.background {
                    ZStack {
                        RoundedRectangle(cornerRadius: 10)
                            .trim(from: 0, to: 0.55)
                            .stroke(isFieldFocused ? .caribe : .gray, lineWidth: isFieldFocused ? 2 : 1)
                        
                        RoundedRectangle(cornerRadius: 10)
                            .trim(from: 0.565 + 0.2 * (labelWidth / width), to: 1)
                            .stroke(isFieldFocused ? .caribe : .gray, lineWidth: isFieldFocused ? 2 : 1)
                    }
                }
            }
    }
}

条件修饰符:

extension View {
    @ViewBuilder
    func `if`<Content: View>(_ condition: Bool, transform: (Self)-> Content) -> some View {
        if condition {
            transform(self)
        } else {
            self
        }
    }
}
swift
  • 1 1 个回答
  • 36 Views

1 个回答

  • Voted
  1. Best Answer
    Benzy Neez
    2024-10-21T00:12:57+08:002024-10-21T00:12:57+08:00

    如果我理解正确的话,要求是在边框中创建一个空间,以便在文本字段中输入任何文本时以较小的尺寸显示标签。

    用来.trim实现这一点会比较困难。我建议,更简单的方法是,当占位符文本移动到边框上方的位置时,为其应用背景填充。

    • 这样,就不需要状态变量来存储标签的宽度。
    • 这反过来可能会解决失去焦点状态的问题FocusState,因为发生的状态更新较少。

    为了实现此功能,占位符需要显示为 中的顶层ZStack。因此,为了防止它拦截手势,您需要.allowsHitTesting(false)对其应用。

    您可以始终将背景应用于占位符。但是,这可能会导致闪烁的光标消失,因为占位符现在是顶层。如果在占位符移动到位时使用过渡效果显示填充的背景,动画效果也会略好一些。

    其他建议:

    • 将.animation修饰符改为使用value: textField.isEmpty,以便它仅在空状态改变时适用。

    • 如果字段没有焦点,则始终以占位符颜色显示较小的标签。

    以下是更新后的示例,以显示其工作原理:

    struct RoundedTextField: View {
        let placeholder: String
        @Binding var text: String
        @FocusState private var isFieldFocused
    
        init(_ placeholder: String, text: Binding<String>) {
            self.placeholder = placeholder
            self._text = text
        }
    
        var body: some View {
            ZStack(alignment: .leading) {
                TextField("", text: $text)
                    .textFieldStyle(RoundedTextFieldStyle(isFieldFocused: isFieldFocused))
                    .focused($isFieldFocused)
    
                Text(placeholder)
                    .foregroundStyle(text.isEmpty || !isFieldFocused ? Color(.placeholderText) : .accentColor)
                    .padding(.horizontal, 8)
                    .background {
                        if !text.isEmpty {
                            Rectangle()
                                .fill(.background)
                                .transition(.scale)
                        }
                    }
                    .padding(.horizontal, 17)
                    .offset(y: text.isEmpty ? 0 : -37)
                    .scaleEffect(text.isEmpty ? 1 : 0.8, anchor: .leading)
                    .allowsHitTesting(false)
            }
            .animation(.default, value: text.isEmpty)
            .padding()
        }
    }
    
    struct RoundedTextFieldStyle: TextFieldStyle {
        var isFieldFocused: Bool
        func _body(configuration: TextField<Self._Label>) -> some View {
            configuration
                .padding(.vertical)
                .padding(.horizontal, 25)
                .frame(height: 60)
                .background {
                    RoundedRectangle(cornerRadius: 10)
                        .stroke(isFieldFocused ? Color.accentColor : .gray, lineWidth: isFieldFocused ? 2 : 1)
                }
        }
    }
    

    动画片

    • 0

相关问题

  • IOS(模拟器)--> 本地 Vapor POST Image/png:Abort.413:有效负载太大

  • 在保存到 Core Data 之前调整图像大小

  • 如何在一个函数中快速处理两个完成处理程序

  • 为什么可编码键和值的字典本身不可编码?

  • 有没有办法将assertionFailure嵌入到'??'中 表达

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve