實(shí)戰(zhàn)需求
macOS SwiftUI 數(shù)據(jù)流之ObservableObject和TextEditor實(shí)現(xiàn)組件內(nèi)數(shù)據(jù)傳遞
本文價值與收獲
看完本文后苞冯,您將能夠作出下面的界面
截屏2021-01-22 下午3.20.37.png
Jietu20210122-152054.gif
看完本文您將掌握的技能
- TextEditor基礎(chǔ)使用
- ObservableObject實(shí)現(xiàn)數(shù)據(jù)多組件傳遞
基礎(chǔ)知識
TextEditor
可以顯示和編輯長格式文本的視圖。
struct TextEditor
總覽
文本編輯器視圖使您可以在應(yīng)用程序的用戶界面中顯示和編輯多行可滾動文本台谢。默認(rèn)情況下,文本編輯器視圖樣式使用從環(huán)境中繼承特性文本,如font(:),和恳不。foregroundColor(:)multilineTextAlignment(_:)
您可以通過在視圖主體中添加實(shí)例來創(chuàng)建文本編輯器,并通過將a傳遞給應(yīng)用程序中的字符串變量來對其進(jìn)行初始化:TextEditorBinding
struct TextEditingView: View {
@State private var fullText: String = "This is some editable text..."
var body: some View {
TextEditor(text: $fullText)
}
}
要設(shè)置文本樣式开呐,請使用標(biāo)準(zhǔn)視圖修飾符來配置系統(tǒng)字體烟勋,設(shè)置自定義字體或更改視圖文本的顏色。
在此示例中筐付,視圖使用自定義字體將編輯器的文本呈現(xiàn)為灰色:
struct TextEditingView: View {
@State private var fullText: String = "This is some editable text..."
var body: some View {
TextEditor(text: $fullText)
.foregroundColor(Color.gray)
.font(.custom("HelveticaNeue", size: 13))
}
}
如果要更改文本的間距或字體縮放比例卵惦,可以使用諸如,的修飾符瓦戚,并根據(jù)空間限制配置視圖顯示文本的方式沮尿。例如,此處的修飾符將線之間的間距設(shè)置為5點(diǎn):lineLimit(:)lineSpacing(:)minimumScaleFactor(:)lineSpacing(:)
struct TextEditingView: View {
@State private var fullText: String = "This is some editable text..."
var body: some View {
TextEditor(text: $fullText)
.foregroundColor(Color.gray)
.font(.custom("HelveticaNeue", size: 13))
.lineSpacing(5)
}
}
實(shí)戰(zhàn)代碼
1较解、主視圖