SwiftUI official tutorial (b)
2. Custom Text View
In order to customize the view of the display, we can change your code, or use inspector
to help us write code.
In the build Landmarks
process, we can use any editor to work: write the source code, modify canvas
, or through inspectors
, no matter what tools to use, the code will be kept up to date.
Next, we use inspector
to customize text view
.
SwiftUI Tutorial
2.1 In the preview, hold down Command
and click the greeting to display the editing window, and then select Inspect
.
Editing window displays the different attributes can be modified, depending on which type of view.
2.2 with inspector
the text changed Turtle Rock
, this is the first landmark name displayed in the app.
SwiftUI Tutorial
2.3 will be Font
amended to Title
.
This change makes the text using the system font, after which it will be able to display the user's preferences and font size settings are correct.
Edit the code by hand to add the .color(.green) modifier; this changes the text’s color to green.
To customize a SwiftUI view, you call methods called modifiers. Modifiers wrap a view to change its display or other properties. Each modifier returns a new view, so it’s common to chain multiple modifiers, stacked vertically.
2.4 在代码中添加 .color(.green)
,将文本的颜色更改为绿色。
如果想自定义 SwiftUI
的 view,我们可以调用一类叫做 modifiers
的方法。这类方法通过包装一个 view 来改变它的显示或者其他属性。每个 modifiers
方法会返回一个新的 view,因此我们可以链式调用多个 modifiers
方法。
ContentView.swift
import SwiftUI
struct ContentView: View {
var body: some View {
Text("Turtle Rock")
.font(.title)
.color(.green)
}
}
struct ContentView_Preview: PreviewProvider {
static var previews: some View {
ContentView()
}
}
view 的真实来源是其实是代码,当我们使用 inspector
修改或删除 modifiers
时,Xcode 会立即更新我们的代码。
2.5 这次我们在代码编辑区按住 Command
,单击 Text
的声明来打开 inspector
,然后选择 Inspect
。单击颜色菜单并且选择 Inherited
,这样文字又变回了黑色。
2.6 注意,Xcode 会自动针对修改来更新代码,例如删除了 .color(.green)
。
ContentView.swift
import SwiftUI
struct ContentView: View {
var body: some View {
Text("Turtle Rock")
.font(.title)
}
}
struct ContentView_Preview: PreviewProvider {
static var previews: some View {
ContentView()
}
}