swift和swiftui
RoundedRectangle复选框 (RoundedRectangle CheckBox)
For the first checkbox, start by creating a new struct view and adding a RoundedRectangle
to it. Use the stroke
function and give it a StrokeStyle
with the line width of your choice:
对于第一个复选框,首先创建一个新的结构视图并向其中添加RoundedRectangle
。 使用stroke
函数,并为其提供StrokeStyle
并带有您选择的线宽:
Embed the RoundedRectangle
inside a ZStack
and add another RoundedRectangle
filled with your choice of color. Make sure that the second RoundedRectangle
is smaller than the first one:
将RoundedRectangle
嵌入到ZStack
并添加另一个填充了您选择的颜色的RoundedRectangle
。 确保第二个RoundedRectangle
小于第一个:
Declare a binding boolean variable called checked
at the top of your struct view. Add a checkmark image underneath your second RoundedRectangle
inside the condition bracket, as below:
在结构视图的顶部声明一个绑定的布尔变量,称为checked
。 在条件括号内的第二个RoundedRectangle
下面添加一个选中标记图像,如下所示:
Now use the same checked
variable to control the rectangles’ colors:
现在使用相同的checked
变量 控制矩形的颜色:
Declare another variable to control the trim
function value of the first RoundedRectangle
. This value will be animated. Have this value inside the animatableData
variable:
声明另一个变量以控制第一个RoundedRectangle
的trim
函数值。 该值将被动画化。 在animatableData
变量中包含以下值:
Change the to:
value of the trim
function to your new variable, trimVal
:
将trim
函数的to:
值更改为新变量trimVal
:
You are done with the CheckBoxView
. Inside your ContentView
, add your CheckBoxView
as a button and pass two state variables (checked
and trimVal
):
您已经完成CheckBoxView
。 在ContentView
内部,将CheckBoxView
添加为按钮,并传递两个状态变量( checked
和trimVal
):
You need to change checked
and trimVal
inside your button. Inside withAnimation
, assign the trimVal
to 1 and use toggle()
to change the checked
boolean value. You can add an else
statement to reverse the animation too:
您需要在按钮内部更改checked
和trimVal
。 内部withAnimation
,分配trimVal
为1,并且使用toggle()
来改变checked
布尔值。 您也可以添加else
语句来反转动画:
You can use an onTapGesture
instead of the button. This will eliminate the flashing that you get with a button:
您可以使用onTapGesture
代替按钮。 这将消除您通过按钮获得的闪烁:
圆形复选框 (Circular CheckBox)
You can go back to your CheckBoxView
and change the shape to a circle, as below:
您可以返回CheckBoxView
并将形状更改为圆形,如下所示:
胶囊复选框 (Capsule CheckBox)
I have two capsules, one overlying the other. Let’s add two variables: width
and removeText
. The width
variable will be used with the capsule’s frames. To make sure the second capsule is smaller than the first one, subtract 10 from the width. Finally, add a text view inside an if
statement, as below:
我有两个胶囊,一个在另一个上。 让我们添加两个变量: width
和removeText
。 width
变量将与胶囊的框架一起使用。 为确保第二个胶囊小于第一个胶囊,请从宽度减去10。 最后,在if
语句内添加一个文本视图,如下所示:
Inside your ContentView
, add the removeText
and width
variables and change the onTapGesture
code to the code below:
在ContentView
,添加removeText
和width
变量,并将onTapGesture
代码更改为onTapGesture
代码:
All done! Thanks for reading!
全做完了! 谢谢阅读!
翻译自: https://medium.com/better-programming/how-to-create-and-animate-checkboxes-in-swiftui-e428fe7cc9c1
swift和swiftui