html 浮动文本
Although the TextField
provides several standard features, you might want to have a floating label as shown above.
尽管TextField
提供了几种标准功能,但是您可能希望具有一个浮动标签,如上所示。
How do you do this with SwiftUI?
您如何使用SwiftUI?
步骤1:建立资料检视 (Step 1: Create a view)
Just the standard business. We need two values: the placeholder text, and the text to display.
只是标准业务。 我们需要两个值:占位符文本和要显示的文本。
步骤2:添加模型 (Step 2: Add a model)
The model is set based on the given initial values.
基于给定的初始值设置模型。
And we need some initialization for it:
我们需要对其进行一些初始化:
步骤3:建立检视 (Step 3: Build the view)
Now we can use the model’s properties to build the basic view:
现在我们可以使用模型的属性来构建基本视图:
What we’re doing here: we overlay the text for the placeholder and the text field, thus separating both. This way, we can move the placeholder how we want.
我们在这里做什么:我们将占位符的文本和文本字段覆盖在一起,从而将两者分开。 这样,我们可以按需要移动占位符。
步骤4:观看TextField内容 (Step 4: Watch the TextField content)
We now enhance the model. This way we can watch live the modifications of the TextField’s content:
现在,我们增强模型。 这样,我们可以实时观看TextField内容的修改:
We attach a .sink
to the @Published
text property. The value
reflects the current string entered to the TextField
and is used to set the currentValue
of the model.
我们将.sink
附加到@Published
文本属性。 该value
反映输入到TextField
的当前字符串,并用于设置模型的currentValue
。
步骤5:对内容的更改做出React (Step 5: React on changes to the content)
In the view, we can now check if the currentValue
is empty, and react accordingly with some transitions and animations:
在视图中,我们现在可以检查currentValue
是否为空,并相应地对一些过渡和动画做出React:
That’s it. This is the full code:
而已。 这是完整的代码:
翻译自: https://levelup.gitconnected.com/swiftui-floating-label-text-field-af04c2eb1a2b
html 浮动文本