(2)SwiftUI 样式修饰符:字体、颜色、内边距与背景
📘 SwiftUI 基础(第二篇)
🎨 样式修饰符:字体、颜色、内边距与背景
在 SwiftUI 中,你可以通过**修饰符(Modifier)**来为组件添加样式。
修饰符就是在视图后面用点语法 .xxx()
链式调用的函数,比如:
Text("Hello, SwiftUI!").font(.title).foregroundColor(.blue)
每个修饰符返回一个新的视图,所以你可以像“叠积木”一样不断叠加它们来形成复杂样式。
一、.font() —— 控制字体样式与大小
📍常用写法:
Text("学习 SwiftUI!").font(.largeTitle) // 系统内置字号:largeTitle, title, body, caption...
📍自定义字体大小:
Text("自定义字号 24").font(.system(size: 24))
📍搭配字体粗细、样式:
Text("加粗 + 斜体").font(.system(size: 20, weight: .bold, design: .rounded))
💡
.font()
通常放在文字组件上,但某些复合组件(比如Button
、Label
)内部的Text
也能继承它。
二、.foregroundColor() —— 控制前景色(通常是文字颜色)
Text("绿色文字").foregroundColor(.green)
也可以用颜色常量或自定义颜色:
Text("自定义颜色").foregroundColor(Color(red: 0.9, green: 0.4, blue: 0.2))
📘 前景色不仅影响文字,还能影响系统图标(
Image(systemName:)
)的颜色:
Image(systemName: "heart.fill").foregroundColor(.red)
三、.padding() —— 添加内边距(内容与边界之间的空隙)
📍基础写法:
Text("带内边距的文字").padding()
默认在四周增加 16 点的空白。
📍指定方向的 padding:
Text("上下多一点空隙").padding(.vertical, 30)
支持 .horizontal
、.vertical
、.top
、.bottom
、.leading
、.trailing
。
📍多个修饰符叠加效果:
Text("有颜色、有边距").foregroundColor(.white).padding().background(Color.blue)
⚠️ 注意顺序!
.padding()
在.background()
前后位置不同,效果完全不一样。
四、.background() —— 背景色或背景视图
📍设置背景颜色:
Text("蓝色背景").padding().background(Color.blue)
📍背景也可以是图片或其他组件:
Text("文字叠在图片上").padding().background(Image("swift-logo").resizable().scaledToFit())
📍组合形状与背景:
Text("圆角背景").padding().background(Color.orange).cornerRadius(10)
五、组合示例 🌈
以下例子演示如何用修饰符组合出一张「信息卡片」:
import SwiftUIstruct ContentView: View {var body: some View {VStack(spacing: 20) {Text("SwiftUI 学习卡片").font(.title).fontWeight(.bold).foregroundColor(.white).padding().frame(maxWidth: .infinity).background(Color.blue).cornerRadius(12)Text("掌握 SwiftUI 修饰符,让你的界面更有设计感!").font(.body).foregroundColor(.gray).padding(.horizontal, 24)Button(action: {}) {Text("开始学习 🚀").font(.headline).foregroundColor(.white).padding().background(Color.green).cornerRadius(10)}}.padding().background(Color(.systemGray6)).cornerRadius(20).shadow(radius: 8)}
}#Preview {ContentView()
}
运行后你会看到一个清新简洁的卡片界面,展示了 .font()
、.foregroundColor()
、.padding()
、.background()
的典型组合。
六、小结 📚
修饰符 | 功能 | 示例 |
---|---|---|
.font() | 控制字体大小、样式 | .font(.title) |
.foregroundColor() | 控制文字或图标颜色 | .foregroundColor(.red) |
.padding() | 添加内边距 | .padding(.horizontal, 20) |
.background() | 设置背景色或背景视图 | .background(Color.blue) |
.cornerRadius() | 圆角(常与背景搭配) | .cornerRadius(10) |