简介
在SwiftUI中,修饰符提供了强大的界面自定义功能。修饰符可以修改视图的显示效果和行为,几乎支持任何视图。
修饰符的格式
在想修饰的视图下方另起一行,点一个点,再点后面写出指令,并打括号,括号里填写详细信息,比如font是这样:
Text("Hello world!")
.font(.title)
更多修饰符
.padding()
:为视图添加内边距,使得视图与其他元素或容器边缘有一定距离。.background()
:设置视图的背景,可以是颜色、渐变或者其他视图。.foregroundColor()
:定义文本或图标的前景色。.font()
:设置文本的字
修饰符的顺序问题
修饰符的顺序对最终的视图布局和渲染有影响。例如,padding
然后background
与background
然后padding
会产生不同的效果:
Text("Padding then Background")
.padding()
.background(Color.green)
Text("Background then Padding")
.background(Color.green)
.padding()
第一个文本首先增加了填充,然后为填充后的视图设置了背景色,因此背景颜色覆盖了填充区域。第二个文本首先设置了背景,然后增加填充,所以背景色仅在文本的原始边界中。
创建自定义修饰符
就像创建视图一样。如果你发现自己重复使用一组特定的修饰符,可以通过创建自定义修饰符来提高代码的重用性。这里有一个简单的例子:
struct MyCustomModifier: ViewModifier {//遵循修饰符的结构
func body(content: Content) -> some View {//定义一个view
content//这就是引用时的view
.font(.title)
.foregroundColor(.white)
.padding()
.background(Color.blue)
.cornerRadius(10)//一些修饰符
}
}
Text("Hello, SwiftUI!")
.modifier(MyCustomModifier())//引用了MyCustomModifier:
而他运行的结果是: