SwiftUI控件

SwiftUI控件

SwiftUI學(xué)習(xí)的內(nèi)容還是很多的,但是我們只對我們項目實戰(zhàn)內(nèi)容所涵蓋的知識點進行講解,
接下來介紹SwiftUI界面元素 、容器 、狀態(tài)和數(shù)據(jù)流。

用戶界面元素

struct Text

顯示一行或多行只讀文本的視圖。

Text("Hamlet")
    .font(.title)
Text("by William Shakespeare")
    .font(.system(size: 12, weight: .light, design: .serif))
    .italic()
let attributedString = try! AttributedString(
    markdown: "_Hamlet_ by William Shakespeare")

var body: some View {
    Text(attributedString)
        .font(.system(size: 12, weight: .light, design: .serif))
}
Text("Brevity is the soul of wit.")
    .frame(width: 100)
    .lineLimit(1)
struct Label

用戶界面項目的標準標簽,由帶有標題的圖標組成。

Label("Lightning", systemImage: "bolt.fill")
Label("Lightning", systemImage: "bolt.fill")
    .labelStyle(.titleOnly)

Label("Lightning", systemImage: "bolt.fill")
    .labelStyle(.iconOnly)

Label("Lightning", systemImage: "bolt.fill")
    .labelStyle(.titleAndIcon)

使用視圖制作標簽,以編程方式組成標簽的圖標,而不是使用預(yù)制圖像。

Label {
    Text(person.fullName)
        .font(.body)
        .foregroundColor(.primary)
    Text(person.title)
        .font(.subheadline)
        .foregroundColor(.secondary)
} icon: {
    Circle()
        .fill(person.profileColor)
        .frame(width: 44, height: 44, alignment: .center)
        .overlay(Text(person.initials))
}
struct TextField

顯示可編輯文本界面的控件。

Label {
    Text(person.fullName)
        .font(.body)
        .foregroundColor(.primary)
    Text(person.title)
        .font(.subheadline)
        .foregroundColor(.secondary)
} icon: {
    Circle()
        .fill(person.profileColor)
        .frame(width: 44, height: 44, alignment: .center)
        .overlay(Text(person.initials))
}

@State private var givenName: String = ""
@State private var familyName: String = ""

var body: some View {
    VStack {
        TextField(
            "Given Name",
            text: $givenName
        )
        .disableAutocorrection(true)
        TextField(
            "Family Name",
            text: $familyName
        )
        .disableAutocorrection(true)
    }
    .textFieldStyle(.roundedBorder)
}

struct Image

顯示圖像的視圖。

Image("Landscape_4")
    .resizable()
    .aspectRatio(contentMode: .fit)
struct Button

啟動操作的控件。


Button(action: signIn) {
    Text("Sign In")
}

    Button {
       print("Action")
       } label: {
           Text("Cancel")
       }
struct Toggle

在開狀態(tài)和關(guān)狀態(tài)之間切換的控件。

@State private var vibrateOnRing = true

var body: some View {
    Toggle("Vibrate on Ring", isOn: $vibrateOnRing)
}

其他:

struct Link

導(dǎo)航到URL的控件。

struct Menu

用于顯示操作菜單的控件。

struct Slider

從有界線性值范圍內(nèi)選擇值的控件。

struct Stepper

執(zhí)行增量和遞減操作的控件。

struct Picker

從一組相互排斥的值中進行選擇的控件。

struct DatePicker

選擇絕對日期的控件。

struct ColorPicker

用于從系統(tǒng)顏色選擇器UI中選擇顏色的控件。

struct ProgressView

顯示完成任務(wù)進展的觀點。

struct Gauge

顯示范圍內(nèi)值的視圖。

容器

容器
布局容器 在容器視圖(如堆棧和網(wǎng)格)內(nèi)水平和垂直排列視圖。使用布局容器來排列用戶界面的元素。堆棧和網(wǎng)格會根據(jù)內(nèi)容或界面維度的變化更新和調(diào)整它們包含的子視圖的位置。您可以將布局容器嵌套到其他布局容器的任何深度,以實現(xiàn)復(fù)雜的布局效果。

struct HStack

將子視圖排列在水平線上。

var body: some View {
    HStack(
        alignment: .top,
        spacing: 10
    ) {
        ForEach(
            1...5,
            id: \.self
        ) {
            Text("Item \($0)")
        }
    }
}

struct VStack

將子子排列成垂直線的視圖。

var body: some View {
    VStack(
        alignment: .leading,
        spacing: 10
    ) {
        ForEach(
            1...10,
            id: \.self
        ) {
            Text("Item \($0)")
        }
    }
}
struct ZStack

覆蓋其子視圖,將它們對齊在兩個軸上。


let colors: [Color] =
    [.red, .orange, .yellow, .green, .blue, .purple]

var body: some View {
    ZStack {
        ForEach(0..<colors.count) {
            Rectangle()
                .fill(colors[$0])
                .frame(width: 100, height: 100)
                .offset(x: CGFloat($0) * 10.0,
                        y: CGFloat($0) * 10.0)
        }
    }
}

<img width = 750 src="第12講-SwiftUI/style/2.jpg">

如果您的視圖只需要簡單的網(wǎng)格或堆棧安排,布局容器就可以,復(fù)雜的可以使用收集容器。

收集容器

將視圖分組到集合容器中,如列表、表和表單。

struct List

一種容器,顯示排列在單個列中的數(shù)據(jù)行,可選地提供選擇一個或多個成員的能力。


var body: some View {
    List {
        Text("A List Item")
        Text("A Second List Item")
        Text("A Third List Item")
    }
}


struct Ocean: Identifiable, Hashable {
    let name: String
    let id = UUID()
}

private var oceans = [
    Ocean(name: "Pacific"),
    Ocean(name: "Atlantic"),
    Ocean(name: "Indian"),
    Ocean(name: "Southern"),
    Ocean(name: "Arctic")
]

@State private var multiSelection = Set<UUID>()

var body: some View {
    NavigationView {
        List(oceans, selection: $multiSelection) {
            Text($0.name)
        }
        .navigationTitle("Oceans")
        .toolbar { EditButton() }
    }
    Text("\(multiSelection.count) selections")
}
struct Table

一種容器,顯示排列在一個或多個列中的數(shù)據(jù)行,可選地提供選擇一個或多個成員的能力。


struct Person: Identifiable {
    let givenName: String
    let familyName: String
    let id = UUID()
}
@State private var people = [
    Person(givenName: "Juan", familyName: "Chavez"),
    Person(givenName: "Mei", familyName: "Chen"),
    Person(givenName: "Tom", familyName: "Clark"),
    Person(givenName: "Gita", familyName: "Kumar"),
]
@State private var sortOrder = [KeyPathComparator(\Person.givenName)]

var body: some View {
    Table(people, sortOrder: $sortOrder) {
        TableColumn("Given Name", value: \.givenName)
        TableColumn("Family Name", value: \.familyName)
    }
    .onChange(of: sortOrder) {
        people.sort(using: $0)
    }
}
struct Form

用于對用于數(shù)據(jù)輸入的控件進行分組的容器,例如在設(shè)置或檢查器中。


var body: some View {
    NavigationView {
        Form {
            Section(header: Text("Notifications")) {
                Picker("Notify Me About", selection: $notifyMeAbout) {
                    Text("Direct Messages").tag(NotifyMeAboutType.directMessages)
                    Text("Mentions").tag(NotifyMeAboutType.mentions)
                    Text("Anything").tag(NotifyMeAboutType.anything)
                }
                Toggle("Play notification sounds", isOn: $playNotificationSounds)
                Toggle("Send read receipts", isOn: $sendReadReceipts)
            }
            Section(header: Text("User Profiles")) {
                Picker("Profile Image Size", selection: $profileImageSize) {
                    Text("Large").tag(ProfileImageSize.large)
                    Text("Medium").tag(ProfileImageSize.medium)
                    Text("Small").tag(ProfileImageSize.small)
                }
                Button("Clear Image Cache") {}
            }
        }
    }
}

struct Group

將內(nèi)容類型的多個實例(如視圖、場景或命令)收集到單個單元中的類型。

var body: some View {
    VStack {
        Group {
            Text("1")
            Text("2")
            Text("3")
            Text("4")
            Text("5")
            Text("6")
            Text("7")
            Text("8")
            Text("9")
            Text("10")
        }
        Text("11")
    }
}
struct ScrollView

可滾動視圖。

var body: some View {
    ScrollView {
        VStack(alignment: .leading) {
            ForEach(0..<100) {
                Text("Row \($0)")
            }
        }
    }
}

演示容器

啟用應(yīng)用程序視圖層次結(jié)構(gòu)不同部分之間的導(dǎo)航。

使用演示容器為您的應(yīng)用程序的用戶界面提供結(jié)構(gòu),使用戶能夠在應(yīng)用程序的各個部分之間輕松移動。例如,您可以使用Navigation在堆視圖中向前和向后導(dǎo)航,使用Tab從選項卡欄中選擇要顯示的視圖,或使用Outline逐步披露樹結(jié)構(gòu)中的視圖。

struct NavigationView

用于顯示代表導(dǎo)航層次結(jié)構(gòu)中可見路徑的視圖堆棧的視圖。

NavigationView {
    List(model.notes) { note in
        NavigationLink(note.title, destination: NoteEditor(id: note.id))
    }
    Text("Select a Note")
}

struct NavigationLink

控制導(dǎo)航演示文稿的視圖。

NavigationLink(
    "Purple",
    destination: ColorDetail(color: .purple),
    isActive: $shouldShowPurple)
struct NavigationBarItem

導(dǎo)航欄的配置,表示導(dǎo)航堆棧頂部的視圖。

分離器

struct Spacer

沿著其包含堆棧布局的主要軸擴展的靈活空間,如果沒有包含在堆棧中,則在兩個軸上擴展。

struct Divider

一種可用于分離其他內(nèi)容的視覺元素。

對齊

struct Alignment

兩個軸的對齊。

struct HorizontalAlignment

沿著水平軸的對齊位置。

struct VerticalAlignment

沿垂直軸的對齊位置。

protocol AlignmentID

用于識別對齊指南的類型。

struct ViewDimensions

視圖的大小及其對齊在自己的坐標空間中引導(dǎo)。

邊緣和區(qū)域

enum Edge

表示矩形一條邊的枚舉。

enum HorizontalEdge

水平軸上的邊緣。

enum VerticalEdge

垂直軸上的邊緣。

struct EdgeInsets

矩形兩側(cè)的插入距離。

struct SafeAreaRegions

一組象征性的安全區(qū)。

struct Anchor

從錨源和特定視圖派生的不透明值。

struct OutlineGroup

從樹結(jié)構(gòu)、已識別數(shù)據(jù)的基礎(chǔ)集合中按需計算視圖和披露組的結(jié)構(gòu)。

struct DisclosureGroup

根據(jù)披露控制狀態(tài)顯示或隱藏另一個內(nèi)容視圖的視圖。

工具欄

struct ToolbarItem

表示可以放置在工具欄或?qū)Ш綑谥械捻椖康哪P汀?/p>

struct ToolbarItemGroup

表示一組ToolbarItem可以放置在工具欄或?qū)Ш綑谥械哪P汀?/p>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容