赞
踩
struct UserCell: View { var user: User var body: some View { VStack { Image(user.image) Text(user.name) Button("Options", action: showOptions) } .accessibilityElement(children: .combine) } } struct Point: CustomStringConvertible { let x: Int, y: Int var description: String { return "(\(x), \(y))" } } let p = Point(x: 21, y: 30) let s = String(describing: p) print(s) // Prints "(21, 30)" struct Point: CustomDebugStringConvertible { let x: Int, y: Int var debugDescription: String { return "(\(x), \(y))" } } let p = Point(x: 21, y: 30) let s = String(reflecting: p) print(s) // Prints "(21, 30)" let numbers = [2, 3, 5, 7] var numbersIterator = numbers.makeIterator() while let num = numbersIterator.next() { print(num) } // Prints "2" // Prints "3" // Prints "5" // Prints "7" @main struct MyApp: App { var body: some Scene { WindowGroup { Text("Hello, world!") } } } @main struct Mail: App { var body: some Scene { WindowGroup { MailViewer() } Settings { SettingsView() } } } @main struct Mail: App { @StateObject private var model = MailModel() var body: some Scene { WindowGroup { MailViewer() .environmentObject(model) // Passed through the environment. } Settings { SettingsView(model: model) // Passed as an observed object. } } } @main struct MyApp: App { var body: some Scene { WindowGroup { Text("Hello, world!") } } } enum MyEnum: Int { case a case b case c } struct MyView: View { @AppStorage("MyEnumValue") private var value = MyEnum.a var body: some View { ... } } enum MyEnum: String { case a case b case c } struct MyView: View { @AppStorage("MyEnumValue") private var value = MyEnum.a var body: some View { ... } } enum MyEnum: String { case a case b case c } struct MyView: View { @AppStorage("MyEnumValue") private var value: MyEnum? var body: some View { ... } } enum MyEnum: Int { case a case b case c } struct MyView: View { @AppStorage("MyEnumValue") private var value: MyEnum? var body: some View { ... } } AsyncImage(url: URL(string: "https://example.com/icon.png")) .frame(width: 200, height: 200) AsyncImage(url: URL(string: "https://example.com/icon.png")) { image in image.resizable() } placeholder: { ProgressView() } .frame(width: 50, height: 50) AsyncImage(url: URL(string: "https://example.com/icon.png")) { phase in if let image = phase.image { image // Displays the loaded image. } else if phase.error != nil { Color.red // Indicates an error. } else { Color.blue // Acts as a placeholder. } } AsyncImage(url: URL(string: "https://example.com/icon.png")) { image in image.resizable(resizingMode: .tile) } placeholder: { Color.green } AsyncImage(url: URL(string: "https://example.com/icon.png")) { phase in if let image = phase.image { image // Displays the loaded image. } else if phase.error != nil { Color.red // Indicates an error. } else { Color.blue // Acts as a placeholder. } } AsyncImage(url: URL(string: "https://example.com/icon.png")) { phase in if let image = phase.image { image // Displays the loaded image. } else if phase.error != nil { Color.red // Indicates an error. } else { Color.blue // Acts as a placeholder. } } let extraOptions = ShippingOptions(rawValue: 255) print(extraOptions.isStrictSuperset(of: .all)) // Prints "true" struct Point: CustomStringConvertible { let x: Int, y: Int var description: String { return "(\(x), \(y))" } } let p = Point(x: 21, y: 30) let s = String(describing: p) print(s) // Prints "(21, 30)" struct PlayButton: View { @Binding var isPlaying: Bool var body: some View { Button(action: { self.isPlaying.toggle() }) { Image(systemName: isPlaying ? "pause.circle" : "play.circle") } } } struct PlayerView: View { var episode: Episode @State private var isPlaying: Bool = false var body: some View { VStack { Text(episode.title) Text(episode.showTitle) PlayButton(isPlaying: $isPlaying) } } } struct PlayButton: View { @Binding var isPlaying: Bool var body: some View { Button(action: { self.isPlaying.toggle() }) { Image(systemName: isPlaying ? "pause.circle" : "play.circle") } } } struct PlayerView: View { var episode: Episode @State private var isPlaying: Bool = false var body: some View { VStack { Text(episode.title) Text(episode.showTitle) PlayButton(isPlaying: $isPlaying) } } } let numbers = [10, 20, 30, 40, 50] if let index = numbers.firstIndex(of: 30) { print(numbers[index ..< numbers.endIndex]) } // Prints "[30, 40, 50]" var c = MyFancyCollection([10, 20, 30, 40, 50]) var i = c.startIndex while i != c.endIndex { c[i] /= 5 i = c.index(after: i) } // c == MyFancyCollection([2, 4, 6, 8, 10]) var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] print(streets[1]) // Prints "Bryant" Button(action: signIn) { Text("Sign In") } Button("Sign In", action: signIn) List { // Cells that show all the current folders. ForEach(folders) { folder in Text(folder.title) } // A cell that, when selected, adds a new folder. Button(action: addItem) { Label("Add Folder", systemImage: "folder.badge.plus") } } .contextMenu { Button("Cut", action: cut) Button("Copy", action: copy) Button("Paste", action: paste) } Button("Delete", role: .destructive, action: delete) HStack { Button("Sign In", action: signIn) Button("Register", action: register) } .buttonStyle(.bordered) struct RedBorderedButtonStyle: PrimitiveButtonStyle { func makeBody(configuration: Configuration) -> some View { Button(configuration) .border(Color.red) } } List { ForEach(items) { item in Text(item.title) .swipeActions { Button(role: .destructive) { delete() } label: { Label("Delete", systemImage: "trash") } } } } .navigationTitle("Shopping List") struct MyButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { configuration.label .font( configuration.role == .cancel ? .title2.bold() : .title2) .foregroundColor( configuration.role == .destructive ? Color.red : nil) } } You can create one of each button using this style to see the effect: VStack(spacing: 20) { Button("Cancel", role: .cancel) {} Button("Delete", role: .destructive) {} Button("Continue") {} } .buttonStyle(MyButtonStyle()) Canvas { context, size in context.stroke( Path(ellipseIn: CGRect(origin: .zero, size: size)), with: .color(.green), lineWidth: 4) } .frame(width: 300, height: 200) .border(Color.blue) struct ScatterPlotView<Mark: View>: View { let rects: [CGRect] let mark: Mark enum SymbolID: Int { case mark } var body: some View { Canvas { context, size in if let mark = context.resolveSymbol(id: SymbolID.mark) { for rect in rects { context.draw(mark, in: rect) } } } symbols: { mark.tag(SymbolID.mark) } .frame(width: 300, height: 200) .border(Color.blue) } } ScatterPlotView(rects: rects, mark: Image(systemName: "circle")) Canvas { context, size in context.stroke( Path(ellipseIn: CGRect(origin: .zero, size: size)), with: .color(.green), lineWidth: 4) } .frame(width: 300, height: 200) .border(Color.blue) * Load a color from an Asset Catalog: ``` let aqua = Color("aqua") // Looks in your app's main bundle by default. ``` * Specify component values, like red, green, and blue; hue, saturation, and brightness; or white level: ``` let skyBlue = Color(red: 0.4627, green: 0.8392, blue: 1.0) let lemonYellow = Color(hue: 0.1639, saturation: 1, brightness: 1) let steelGray = Color(white: 0.4745) ``` * Create a color instance from another color, like a <doc://com.apple.documentation/documentation/UIKit/UIColor> or an <doc://com.apple.documentation/documentation/AppKit/NSColor>: ``` #if os(iOS) let linkColor = Color(uiColor: .link) #elseif os(macOS) let linkColor = Color(nsColor: .linkColor) #endif ``` * Use one of a palette of predefined colors, like ``ShapeStyle/black``, ``ShapeStyle/green``, and ``ShapeStyle/purple``. Image(systemName: "leaf.fill") .foregroundStyle(Color.green) ZStack { skyBlue Image(systemName: "sun.max.fill") .foregroundStyle(lemonYellow) } .frame(width: 200, height: 100) Text("Accent Color") .foregroundStyle(Color.accentColor) struct Hello: View { var body: some View { ZStack { Color("background") Text("Hello, world!") .foregroundStyle(Color("foreground")) } .frame(width: 200, height: 100) } } struct Box: View { var body: some View { Color(UIColor.link) .frame(width: 200, height: 100) } } struct Box: View { var body: some View { Color(uiColor: .link) .frame(width: 200, height: 100) } } struct FormattingControls: View { @State private var bgColor = Color(.sRGB, red: 0.98, green: 0.9, blue: 0.2) var body: some View { VStack { ColorPicker("Alignment Guides", selection: $bgColor) } } } final class Settings: ObservableObject { @Published var alignmentGuideColor = Color(.sRGB, red: 0.98, green: 0.9, blue: 0.2) } struct FormattingControls: View { @State private var settings = Settings() var body: some View { VStack { // Other formatting controls. ColorPicker("Alignment Guides", selection: $settings.alignmentGuideColor ) } } } func showColorPicker(_ title: String, color: Binding<Color>) { ColorPicker(title, selection: color) } let selectedSize = PaperSize.Letter print(selectedSize.rawValue) // Prints "Letter" print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!) // Prints "true" func selectHearts() { // Act on hearts selection. } func selectClubs() { ... } func selectSpades() { ... } func selectDiamonds() { ... } let menuItems = ContextMenu { Button("♥️ - Hearts", action: selectHearts) Button("♣️ - Clubs", action: selectClubs) Button("♠️ - Spades", action: selectSpades) Button("♦️ - Diamonds", action: selectDiamonds) } struct ContextMenuMenuItems: View { private var shouldShowMenu = true var body: some View { VStack { Text("Favorite Card Suit") .padding() .contextMenu(shouldShowMenu ? menuItems : nil) } } } struct RedBorderControlGroupStyle: ControlGroupStyle { func makeBody(configuration: Configuration) -> some View { ControlGroup(configuration) .border(Color.red) } } @State private var date = Date() var body: some View { DatePicker( "Start Date", selection: $date, displayedComponents: [.date] ) } @State private var date = Date() let dateRange: ClosedRange<Date> = { let calendar = Calendar.current let startComponents = DateComponents(year: 2021, month: 1, day: 1) let endComponents = DateComponents(year: 2021, month: 12, day: 31, hour: 23, minute: 59, second: 59) return calendar.date(from:startComponents)! ... calendar.date(from:endComponents)! }() var body: some View { DatePicker( "Start Date", selection: $date, in: dateRange, displayedComponents: [.date, .hourAndMinute] ) } @State private var date = Date() var body: some View { DatePicker( "Start Date", selection: $date, displayedComponents: [.date] ) .datePickerStyle(.graphical) } let selectedSize = PaperSize.Letter print(selectedSize.rawValue) // Prints "Letter" print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!) // Prints "true" struct ToggleStates { var oneIsOn: Bool = false var twoIsOn: Bool = true } @State private var toggleStates = ToggleStates() @State private var topExpanded: Bool = true var body: some View { DisclosureGroup("Items", isExpanded: $topExpanded) { Toggle("Toggle 1", isOn: $toggleStates.oneIsOn) Toggle("Toggle 2", isOn: $toggleStates.twoIsOn) DisclosureGroup("Sub-items") { Text("Sub-item 1") } } } struct SheetView: View { @Environment(\.dismiss) var dismiss var body: some View { NavigationView { SheetContents() .toolbar { Button("Done") { dismiss() } } } } } @main struct MyApp: App { var body: some Scene { DocumentGroup(newDocument: TextFile()) { file in ContentView(document: file.$document) } } } @main struct MyApp: App { var body: some Scene { DocumentGroup(viewing: MyImageFormatDocument.self) { MyImageFormatViewer(image: $0.document) } } } @main struct MyApp: App { var body: some Scene { DocumentGroup(newDocument: TextFile()) { group in ContentView(document: group.$document) } DocumentGroup(viewing: MyImageFormatDocument.self) { group in MyImageFormatViewer(image: group.document) } } } @main struct MyApp: App { var body: some Scene { DocumentGroup(newDocument: TextFile()) { file in ContentView(document: file.$document) } } } @main struct MyApp: App { var body: some Scene { DocumentGroup(viewing: MyImageFormatDocument.self) { file in MyImageFormatViewer(image: file.document) } } } struct DragGestureView: View { @State var isDragging = false var drag: some Gesture { DragGesture() .onChanged { _ in self.isDragging = true } .onEnded { _ in self.isDragging = false } } var body: some View { Circle() .fill(self.isDragging ? Color.red : Color.blue) .frame(width: 100, height: 100, alignment: .center) .gesture(drag) } } print(PaperSize(rawValue: "Legal")) // Prints "Optional("PaperSize.Legal")" print(PaperSize(rawValue: "Tabloid")) // Prints "nil" let selectedSize = PaperSize.Letter print(selectedSize.rawValue) // Prints "Letter" print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!) // Prints "true" @State private var fruits = [ "Apple", "Banana", "Papaya", "Mango" ] var body: some View { NavigationView{ List { ForEach( fruits, id: \.self ) { fruit in Text(fruit) } .onDelete { self.deleteFruit(at :$0) } .onMove { self.moveFruit(from: $0, to: $1) } } .navigationTitle("Fruits") .toolbar { EditButton() } } } EllipticalGradient( gradient: .init(colors: [.blue, .green]), center: .topLeading, startRadiusFraction: 0, endRadiusFraction: 1) EllipticalGradient( colors: [.blue, .green], center: .topLeading, startRadiusFraction: 0, endRadiusFraction: 1) EllipticalGradient( stops: [ .init(color: .blue, location: 0.0), .init(color: .green, location: 0.9), .init(color: .green, location: 1.0), ], center: .topLeading, startRadiusFraction: 0, endRadiusFraction: 1) struct EmphasizedLayout: ViewModifier { func body(content: Content) -> some View { content .background(Color.yellow) .border(Color.red) } } struct ContentView: View { var body: some View { Text("Hello, World!") .modifier(modifier) } var modifier: some ViewModifier { #if DEBUG return EmphasizedLayout() #else return EmptyModifier() #endif } } let progressView = ProgressView() print("\(type(of:progressView))") // Prints: ProgressView<EmptyView, EmptyView> @Environment(\.colorScheme) var colorScheme: ColorScheme if colorScheme == .dark { // Checks the wrapped value. DarkContent() } else { LightContent() } struct MyView: View { @Environment(\.colorScheme) var colorScheme: ColorScheme // ... } @Environment(\.colorScheme) var colorScheme: ColorScheme var body: some View { if colorScheme == .dark { DarkContent() } else { LightContent() } } private struct MyEnvironmentKey: EnvironmentKey { static let defaultValue: String = "Default value" } extension EnvironmentValues { var myCustomValue: String { get { self[MyEnvironmentKey.self] } set { self[MyEnvironmentKey.self] = newValue } } } MyView() .environment(\.myCustomValue, "Another string") extension View { func myCustomValue(_ myCustomValue: String) -> some View { environment(\.myCustomValue, myCustomValue) } } MyView() .myCustomValue("Another string") struct MyView: View { @Environment(\.myCustomValue) var customValue: String var body: some View { Text(customValue) // Displays "Another value". } } @Environment(\.locale) var locale: Locale MyView() .environment(\.lineLimit, 2) MyView() .lineLimit(2) MyView() .popover(isPresented: $isPopped) { PopoverContent() .preferredColorScheme(.dark) } private struct MyEnvironmentKey: EnvironmentKey { static let defaultValue: String = "Default value" } extension EnvironmentValues { var myCustomValue: String { get { self[MyEnvironmentKey.self] } set { self[MyEnvironmentKey.self] = newValue } } } extension View { func myCustomValue(_ myCustomValue: String) -> some View { environment(\.myCustomValue, myCustomValue) } } private struct MyEnvironmentKey: EnvironmentKey { static let defaultValue: String = "Default value" } extension EnvironmentValues { var myCustomValue: String { get { self[MyEnvironmentKey.self] } set { self[MyEnvironmentKey.self] = newValue } } } extension View { func myCustomValue(_ myCustomValue: String) -> some View { environment(\.myCustomValue, myCustomValue) } } HStack { Image(systemName: "heart") Image(systemName: "heart") .environment(\.symbolVariants, .none) } .symbolVariant(.fill) struct ContentView: View { @State var text = "" var body: some View { SearchReadingView() .searchable(text: $text) } } struct SearchReadingView: View { @Environment(\.isSearching) var isSearching var body: some View { if isSearching { Text("Searching!") } else { Text("Not searching.") } } NavigationView { MyList() .searchable(text: $text) } struct MyList: View { @State private var isPresented = false @Environment(\.isSearching) private var isSearching var body: some View { Text("Main List") .frame(maxWidth: .infinity, maxHeight: .infinity) .overlay { if isSearching { Button { isPresented = true } label: { Text("Present") .frame( maxWidth: .infinity, maxHeight: .infinity ) .background() } .sheet(isPresented: $isPresented) { NavigationView { DetailView() } } } } } } struct DetailView: View { @Environment(\.dismiss) private var dismiss @Environment(\.dismissSearch) private var dismissSearch var body: some View { Text("Detail Content") .toolbar { Button("Add") { dismiss() dismissSearch() } } } } Text("Visit [Example Co](https://www.example.com) for details.") .environment(\.openURL, OpenURLAction { url in handleURL(url) return .handled }) private struct MyButtonStyle: ButtonStyle { @Environment(\.keyboardShortcut) private var shortcut: KeyboardShortcut? func makeBody(configuration: Configuration) -> some View { let labelFont = Font.body .weight(shortcut == .defaultAction ? .bold : .regular) configuration.label .font(labelFont) } } HStack { Text("This is a very long label:") .lineLimit(1) .minimumScaleFactor(0.5) TextField("My Long Text Field", text: $myTextField) .frame(width: 250, height: 50, alignment: .center) } let numbers = [2, 3, 5, 7] var numbersIterator = numbers.makeIterator() while let num = numbersIterator.next() { print(num) } // Prints "2" // Prints "3" // Prints "5" // Prints "7" @FetchRequest(sortDescriptors: [SortDescriptor(\.time, order: .reverse)]) private var quakes: FetchedResults<Quake> @FetchRequest(fetchRequest: request) private var quakes: FetchedResults<Quake> ContentView() .environment( \.managedObjectContext, QuakesProvider.shared.container.viewContext) @FetchRequest(fetchRequest: request) private var quakes: FetchedResults<Quake> Text("Found \(quakes.count) earthquakes") var fetchRequest = FetchRequest<Quake>(fetchRequest: request) var quakes: FetchedResults<Quake> { fetchRequest.wrappedValue } @FetchRequest(sortDescriptors: [SortDescriptor(\.time, order: .reverse)]) private var quakes: FetchedResults<Quake> Table(quakes, sortOrder: $quakes.sortDescriptors) { TableColumn("Place", value: \.place) TableColumn("Time", value: \.time) { quake in Text(quake.time, style: .time) } } @State private var query = "" .onChange(of: query) { value in quakes.nsPredicate = query.isEmpty ? nil : NSPredicate(format: "place CONTAINS %@", value) } TextField("Filter", text: $query) @FetchRequest(sortDescriptors: [SortDescriptor(\.time, order: .reverse)]) private var quakes: FetchedResults<Quake> Table(quakes, sortOrder: $quakes.sortDescriptors) { TableColumn("Place", value: \.place) TableColumn("Time", value: \.time) { quake in Text(quake.time, style: .time) } } extension Quake { var request: NSFetchRequest<Quake> { let request = NSFetchRequest<Quake>(entityName: "Quake") request.sortDescriptors = [ NSSortDescriptor( keyPath: \Quake.time, ascending: true)] request.fetchLimit = 1000 return request } } @FetchRequest(fetchRequest: Quake.request) private var quakes: FetchedResults<Quake> @FetchRequest(sortDescriptors: [SortDescriptor(\.time, order: .reverse)]) private var quakes: FetchedResults<Quake> List(quakes) { quake in NavigationLink(destination: QuakeDetail(quake: quake)) { QuakeRow(quake: quake) } } ContentView() .environment( \.managedObjectContext, QuakesProvider.shared.container.viewContext) struct LoginForm { enum Field: Hashable { case username case password } @State private var username = "" @State private var password = "" @FocusState private var focusedField: Field? var body: some View { Form { TextField("Username", text: $username) .focused($focusedField, equals: .username) SecureField("Password", text: $password) .focused($focusedField, equals: .password) Button("Sign In") { if username.isEmpty { focusedField = .username } else if password.isEmpty { focusedField = .password } else { handleLogin(username, password) } } } } } struct ContentView: View { enum Field: Hashable { case name case fullName } @FocusState private var focusedField: Field? var body: some View { TextField("Full Name", ...) .focused($focusedField, equals: .name) .focused($focusedField, equals: .fullName) } } struct ContentView: View { enum Field: Hashable { case name case fullName } @FocusState private var focusedField: Field? var body: some View { TextField("Name", ...) .focused($focusedField, equals: .name) TextField("Full Name", ...) .focused($focusedField, equals: .name) // incorrect re-use of .name } } struct Sidebar: View { @State private var filterText = "" @FocusState private var isFiltering: Bool var body: some View { VStack { Button("Filter Sidebar Contents") { isFiltering = true } TextField("Filter", text: $filterText) .focused($isFiltering) } } } // Use native Core Text API to create desired ctFont. let ctFont = CTFontCreateUIFontForLanguage(.system, 12, nil)! // Create SwiftUI Text with the CTFont instance. let text = Text("Hello").font(Font(ctFont)) private struct NamedFont: Identifiable { let name: String let font: Font var id: String { name } } private let namedFonts: [NamedFont] = [ NamedFont(name: "Large Title", font: .largeTitle), NamedFont(name: "Title", font: .title), NamedFont(name: "Headline", font: .headline), NamedFont(name: "Body", font: .body), NamedFont(name: "Caption", font: .caption) ] var body: some View { ForEach(namedFonts) { namedFont in Text(namedFont.name) .font(namedFont.font) } } 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") {} } } } } var body: some View { Spacer() HStack { Spacer() Form { 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) Picker("Profile Image Size:", selection: $profileImageSize) { Text("Large").tag(ProfileImageSize.large) Text("Medium").tag(ProfileImageSize.medium) Text("Small").tag(ProfileImageSize.small) } .pickerStyle(.inline) Button("Clear Image Cache") {} } Spacer() } Spacer() } let selectedSize = PaperSize.Letter print(selectedSize.rawValue) // Prints "Letter" print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!) // Prints "true" struct SimpleLongPressGestureView: View { @GestureState var isDetectingLongPress = false var longPress: some Gesture { LongPressGesture(minimumDuration: 3) .updating($isDetectingLongPress) { currentState, gestureState, transaction in gestureState = currentState } } var body: some View { Circle() .fill(self.isDetectingLongPress ? Color.red : Color.green) .frame(width: 100, height: 100, alignment: .center) .gesture(longPress) } } Canvas { context, size in context.fill( Path(ellipseIn: CGRect(origin: .zero, size: size)), with: .color(.green)) } .frame(width: 300, height: 200) let halfSize = size.applying(CGAffineTransform(scaleX: 0.5, y: 0.5)) context.clip(to: Path(CGRect(origin: .zero, size: halfSize))) context.fill( Path(ellipseIn: CGRect(origin: .zero, size: size)), with: .color(.green)) // Create a copy of the context to draw a clipped ellipse. var maskedContext = context let halfSize = size.applying(CGAffineTransform(scaleX: 0.5, y: 0.5)) maskedContext.clip(to: Path(CGRect(origin: .zero, size: halfSize))) maskedContext.fill( Path(ellipseIn: CGRect(origin: .zero, size: size)), with: .color(.green)) // Go back to the original context to draw the rectangle. let origin = CGPoint(x: size.width / 4, y: size.height / 4) context.fill( Path(CGRect(origin: origin, size: halfSize)), with: .color(.blue)) enum PaperSize: String { case A4, A5, Letter, Legal } print(PaperSize(rawValue: "Legal")) // Prints "Optional("PaperSize.Legal")" print(PaperSize(rawValue: "Tabloid")) // Prints "nil" Group { Text("SwiftUI") Text("Combine") Text("Swift System") } .font(.headline) Group { if isLoggedIn { WelcomeView() } else { LoginView() } } .navigationBarTitle("Start") 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") } } var body: some View { GroupBox(label: Label("End-User Agreement", systemImage: "building.columns") ) { ScrollView(.vertical, showsIndicators: true) { Text(agreementText) .font(.footnote) } .frame(height: 100) Toggle(isOn: $userAgreed) { Text("I agree to the above terms") } } } struct PinkBorderGroupBoxStyle: GroupBoxStyle { func makeBody(configuration: Configuration) -> some View { GroupBox(configuration) .border(Color.pink) } } var body: some View { HStack( alignment: .top, spacing: 10 ) { ForEach( 1...5, id: \.self ) { Text("Item \($0)") } } } print(PaperSize(rawValue: "Legal")) // Prints "Optional("PaperSize.Legal")" print(PaperSize(rawValue: "Tabloid")) // Prints "nil" let selectedSize = PaperSize.Letter print(selectedSize.rawValue) // Prints "Letter" print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!) // Prints "true" Image("Landscape_4") .resizable() .aspectRatio(contentMode: .fit) Text("Water wheel") Image("dot_green") .renderingMode(.original) Image("dot_green") .renderingMode(.template) ```swift HStack { Image(systemName: "person.crop.circle.badge.plus") Image(systemName: "person.crop.circle.badge.plus") .renderingMode(.original) .foregroundColor(.blue) Image(systemName: "person.crop.circle.badge.plus") .renderingMode(.template) .foregroundColor(.blue) } .font(.largeTitle)
enum PaperSize: String {
case A4, A5, Letter, Legal
}
print(PaperSize(rawValue: "Legal"))
// Prints "Optional("PaperSize.Legal")"
print(PaperSize(rawValue: "Tabloid"))
// Prints "nil"
HStack { Image(systemName: "swift").imageScale(.small); Text("Small") }
HStack { Image(systemName: "swift").imageScale(.medium); Text("Medium") }
HStack { Image(systemName: "swift").imageScale(.large); Text("Large") }
struct CircleImage_Previews: PreviewProvider {
static var previews: some View {
CircleImage()
.previewInterfaceOrientation(.landscapeRight)
}
}
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)
struct RedBorderedLabelStyle: LabelStyle {
func makeBody(configuration: Configuration) -> some View {
Label(configuration)
.border(Color.red)
}
}
VStack {
Label("Rain", systemImage: "cloud.rain")
Label("Snow", systemImage: "snow")
Label("Sun", systemImage: "sun.max")
}
.labelStyle(.iconOnly)
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 RedBorderedLabelStyle: LabelStyle {
func makeBody(configuration: Configuration) -> some View {
Label(configuration)
.border(Color.red)
}
}
Label("Lightning", systemImage: "bolt.fill")
.labelStyle(.titleAndIcon)
VStack {
Label("Rain", systemImage: "cloud.rain")
Label("Snow", systemImage: "snow")
Label("Sun", systemImage: "sun.max")
}
.labelStyle(.titleAndIcon)
var rows: [GridItem] =
Array(repeating: .init(.fixed(20)), count: 2)
ScrollView(.horizontal) {
LazyHGrid(rows: rows, alignment: .top) {
ForEach((0...79), id: \.self) {
let codepoint = $0 + 0x1f600
let codepointString = String(format: "%02X", codepoint)
Text("\(codepointString)")
.font(.footnote)
let emoji = String(Character(UnicodeScalar(codepoint)!))
Text("\(emoji)")
.font(.largeTitle)
}
}
}
ScrollView(.horizontal) {
LazyHStack(alignment: .top, spacing: 10) {
ForEach(1...100, id: \.self) {
Text("Column \($0)")
}
}
}
var columns: [GridItem] =
Array(repeating: .init(.flexible()), count: 2)
ScrollView {
LazyVGrid(columns: columns) {
ForEach((0...79), id: \.self) {
let codepoint = $0 + 0x1f600
let codepointString = String(format: "%02X", codepoint)
Text("\(codepointString)")
let emoji = String(Character(UnicodeScalar(codepoint)!))
Text("\(emoji)")
}
}.font(.largeTitle)
}
ScrollView {
LazyVStack(alignment: .leading) {
ForEach(1...100, id: \.self) {
Text("Row \($0)")
}
}
}
Link("View Our Terms of Service",
destination: URL(string: "https://www.example.com/TOS.html")!)
func marketingLink(_ callToAction: String) -> Link {
Link(callToAction,
destination: URL(string: "https://www.example.com/")!)
}
var body: some View {
List {
Text("A List Item")
Text("A Second List Item")
Text("A Third List Item")
}
}
struct Ocean: Identifiable {
let name: String
let id = UUID()
}
private var oceans = [
Ocean(name: "Pacific"),
Ocean(name: "Atlantic"),
Ocean(name: "Indian"),
Ocean(name: "Southern"),
Ocean(name: "Arctic")
]
var body: some View {
List(oceans) {
Text($0.name)
}
}
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 Ocean: Identifiable, Hashable {
let name: String
let id = UUID()
let stats: [String: String]
}
class OceanStore: ObservableObject {
@Published var oceans = [Ocean]()
func loadStats() async -> Void {}
}
@EnvironmentObject var store: OceanStore
var body: some View {
NavigationView {
List(store.oceans) { ocean in
HStack {
Text(ocean.name)
StatsSummary(stats: ocean.stats) // A custom view for showing statistics.
}
}
.refreshable {
await store.loadStats()
}
.navigationTitle("Oceans")
}
}
struct ContentView: View {
struct Sea: Hashable, Identifiable {
let name: String
let id = UUID()
}
struct OceanRegion: Identifiable {
let name: String
let seas: [Sea]
let id = UUID()
}
private let oceanRegions: [OceanRegion] = [
OceanRegion(name: "Pacific",
seas: [Sea(name: "Australasian Mediterranean"),
Sea(name: "Philippine"),
Sea(name: "Coral"),
Sea(name: "South China")]),
OceanRegion(name: "Atlantic",
seas: [Sea(name: "American Mediterranean"),
Sea(name: "Sargasso"),
Sea(name: "Caribbean")]),
OceanRegion(name: "Indian",
seas: [Sea(name: "Bay of Bengal")]),
OceanRegion(name: "Southern",
seas: [Sea(name:"Weddell")]),
OceanRegion(name: "Arctic",
seas: [Sea(name: "Greenland")])
]
@State private var singleSelection : UUID?
var body: some View {
NavigationView {
List(selection: $singleSelection){
ForEach(oceanRegions) { region in
Section(header: Text("Major \(region.name) Ocean Seas")) {
ForEach(region.seas) { sea in
Text(sea.name)
}
}
}
}
.navigationTitle("Oceans and Seas")
.toolbar { EditButton() }
}
}
}
struct ContentView: View {
struct FileItem: Hashable, Identifiable, CustomStringConvertible {
var id: Self { self }
var name: String
var children: [FileItem]? = nil
var description: String {
switch children {
case nil:
return "声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/236184?site
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。