Giter VIP home page Giter VIP logo

setting's Introduction

Header image

Compose beautiful preference panels.

  • Simple but powerful syntax (powered by result builders).
  • Create nested pages and groups.
  • Fully searchable.
  • Native integration with SwiftUI and AppStorage.
  • Comes with pre-made components: Toggle, Button, Slider, etc...
  • Style components with native SwiftUI modifiers.
  • Show and hide components dynamically.
  • Add your own custom SwiftUI views.
  • Works on iOS and macOS.

Screenshots of views created with Setting

Screenshots of a nested page and search results

Installation

Setting is available via the Swift Package Manager. Requires iOS 15+ or macOS Monterey and up.

https://github.com/aheze/Setting

Usage

import Setting
import SwiftUI

struct PlaygroundView: View {
    /// Setting supports `@State`, `@AppStorage`, `@Published`, and more!
    @AppStorage("isOn") var isOn = true

    var body: some View {
        /// Start things off with `SettingStack`.
        SettingStack {
            /// This is the main settings page.
            SettingPage(title: "Playground") {
                /// Use groups to group components together.
                SettingGroup(header: "Main Group") {
                    /// Use any of the pre-made components...
                    SettingToggle(title: "This value is persisted!", isOn: $isOn)

                    /// ...or define your own ones!
                    SettingCustomView {
                        Image("Logo")
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .frame(width: 160)
                            .padding(20)
                    }

                    /// Nest `SettingPage` inside other `SettingPage`s!
                    SettingPage(title: "Advanced Settings") {
                        SettingText(title: "I show up on the next page!")
                    }
                }
            }
        }
    }
}

The result, a generated settings page. Clicking on "Advanced Settings" presents a new page.

Examples

View more examples in the example app.

struct PlaygroundView: View {
    var body: some View {
        SettingStack {
            SettingPage(title: "Playground") {
                SettingGroup {
                    SettingText(title: "Hello!")
                }
            }
        }
    }
}

Settings view rendered with "Hello!" label

SettingStack {
    SettingPage(title: "Playground") {
        SettingGroup {
            SettingText(title: "Hello!")
        }

        SettingGroup {
            SettingPage(title: "First Page") {}
                .previewIcon("star")

            SettingPage(title: "Second Page") {}
                .previewIcon("sparkles")

            SettingPage(title: "Third Page") {}
                .previewIcon("leaf.fill")
        }
    }
}

Settings view rendered with 3 row links

struct PlaygroundView: View {
    @AppStorage("isOn") var isOn = true
    @AppStorage("value") var value = Double(5)

    var body: some View {
        SettingStack {
            SettingPage(title: "Playground") {
                SettingGroup {
                    SettingToggle(title: "On", isOn: $isOn)
                }

                SettingGroup(header: "Slider") {
                    SettingSlider(
                        value: $value,
                        range: 0 ... 10
                    )
                }
            }
        }
    }
}

Settings view rendered with toggle and slider

struct PlaygroundView: View {
    @AppStorage("index") var index = 0

    var body: some View {
        SettingStack {
            SettingPage(title: "Playground") {
                SettingGroup {
                    SettingPicker(
                        title: "Picker",
                        choices: ["A", "B", "C", "D"],
                        selectedIndex: $index
                    )
                    SettingPicker(
                        title: "Picker with menu",
                        choices: ["A", "B", "C", "D"],
                        selectedIndex: $index,
                        choicesConfiguration: .init(
                            pickerDisplayMode: .menu
                        )
                    )
                }
            }
        }
    }
}

Settings view rendered with picker

SettingStack {
    SettingPage(title: "Playground") {
        SettingCustomView {
            Color.blue
                .opacity(0.1)
                .cornerRadius(12)
                .overlay {
                    Text("Put anything here!")
                        .foregroundColor(.blue)
                        .font(.title.bold())
                }
                .frame(height: 150)
                .padding(.horizontal, 16)
        }
    }
}

Settings view rendered with "Put anything here!" label

Notes

  • If multiple components have the same title, use the id parameter to make sure everything gets rendered correctly.
SettingText(id: "Announcement 1", title: "Hello!")
SettingText(id: "Announcement 2", title: "Hello!")
  • Setting comes with if-else support!
SettingToggle(title: "Turn on", isOn: $isOn)

if isOn {
    SettingText("I'm turned on!")
}
  • Wrap components in SettingCustomView to style them.
SettingCustomView {
    SettingText(title: "I'm bold!")
        .bold()
}
  • Want to split up a Setting into multiple variables/files? Just use @SettingBuilder.
struct ContentView: View {
    var body: some View {
        SettingStack {
            SettingPage(title: "Settings") {
                general
                misc
            }
        }
    }
    
    @SettingBuilder var general: some Setting {
        SettingPage(title: "General") {
            SettingText(title: "General Settings")
        }
    }
    
    @SettingBuilder var misc: some Setting {
        SettingPage(title: "Misc") {
            SettingText(title: "Misc Settings")
        }
    }
}
  • Need to store custom structs in AppStorage? Check out @IanKeen's awesome gist!

  • You can pass in a custom SettingViewModel instance for finer control.

struct PlaygroundView: View {
    @StateObject var settingViewModel = SettingViewModel()

    var body: some View {
        SettingStack(settingViewModel: settingViewModel) {
            SettingPage(title: "Playground") {
                SettingGroup {
                    SettingText(title: "Welcome to Setting!")
                }
            }
        } customNoResultsView: {
            VStack(spacing: 20) {
                Image(systemName: "xmark")
                    .font(.largeTitle)

                Text("No results for '\(settingViewModel.searchText)'")
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
        }
    }
}

Settings view rendered with "Put anything here!" label


Community

Author Contributing Need Help?
Setting is made by aheze. All contributions are welcome. Just fork the repo, then make a pull request. Open an issue or join the Discord server. You can also ping me on Twitter.

License

MIT License

Copyright (c) 2023 A. Zheng

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

setting's People

Contributors

aheze avatar javiergarmon avatar johjakob avatar matteozappia avatar mpdifran avatar n3d1117 avatar orchetect avatar saik0s avatar tkgka avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

setting's Issues

Unable to use ForEach

struct ContentView: View {
    var body: some View {
            SettingStack {
                SettingPage(title: "Playground") {
                    SettingGroup(header: "Group 1") {
                        ForEach(0..<5) { i in
                            SettingCustomView {
                                Text("Hello Group \(i)")
                            }
                        }
                    }
                }
            }
        }
    }
}

Error: Static method 'buildExpression' requires that 'SettingCustomView' conform to 'View'

Possible useful resources:

[BUG] navigation using NSHostingController within macOS app target does not allow for back nav

AppKit applications can embed SwiftUI views, which is very handy for code-sharing between iOS and macOS targets within the same application project.

Unfortunately, this framework does not take this situation into account and implements a WindowGroup using a SwiftUI Scene, which assumes the hosting application is also a SwiftUI application.

As a result, within an AppKit / Cocoa application, we are able to successfully present the ContentView, but any navigation within the ContentView (from the example project) within a macOS app using NSHostingController does have any automatic navigation controls like the back-button, nor any other sort of method of navigating backwards.

I saw another issue opened with a similar question, but the suggestion to just use the framework as a .sheet is not an acceptable answer for a number of reasons, but mainly because it doesn't work for my application's consistent design approach.

I am fairly motivated to make this function properly, so this isn't just a complaint-- I have forked the repo and will attempt to implement support for my use case on a lightest-possible-touch basis.

@aheze will you consider this sort of improvement for review if I issue a PR?

Thanks,
Dan

Hiding search by default placement: .navigationBarDrawer(displayMode: .automatic))

Hi, thank you for this nice project. I am just wondering about the possibility of hiding the search by default and make it visible when the user starts to scroll just like in the Settings.app.

I tried to modify the main view in SettingStack struct as below but didn't work, usually it does. Any other changes I need to do?

        .if(isSearchable) { view in
            view
                .searchable(text: $settingViewModel.searchText, placement: .navigationBarDrawer(displayMode: .automatic))
        }

Theme entire setting stack

Would be nice to set the background colour of certain items throughout the SettingStack, rather than having to set each and every SettingPage and SettingGroup

Search Bar in SettingPicker

Would it be possible to integrate a search bar into SettingPicket so that if I want to I can have a search bar enabled when clicking on a picker?

Generic SettingView

The problem

Currently SettingView renders each element via a huge switch.

Huge `switch` statement that checks if the element is a text, button, toggle, page, etc.

This has several limitations:

No support for custom Settings

The switch statement checks against SettingText, SettingButton, SettingToggle, etc. Say we had our own element called SettingLabel:

struct SettingLabel: View, Setting {
    var id: AnyHashable?

    var body: some View {
        Text("Hello!")
    }
}

This would fall through in the switch statement and error out.

switch setting {
case let text as SettingText:
    text
case let button as SettingButton:
    button
case let toggle as SettingToggle:
    /* ... */
default:
    Text("Unsupported setting, please file a bug report.")
}

Text displaying "Unsupported setting, please file a bug report"

Limited customization (no subclass / composing support)

This is related to the above issue. Let's say you want to make a bunch of SettingTexts blue. Right now you need to do this:

SettingText(title: "Hello", foregroundColor: .blue)
SettingText(title: "Hello again", foregroundColor: .blue)
SettingText(title: "Bruh", foregroundColor: .blue)

Ideally you'd be able to make a new element that conforms from Setting.

struct BlueSettingText: View, Setting {
    var id: AnyHashable?
    var title: String

    var body: some View {
        SettingText(title: title, foregroundColor: .blue)
    }
}

/* ... */

BlueSettingText(title: "Hello")
BlueSettingText(title: "Hello again")
BlueSettingText(title: ":)")

This code compiles, but it will fall through in the above mentioned issue with the switch statement.

Reliance on stable ID identifiers

You might have noticed all the var id: AnyHashable?s floating around. This is because of the ForEach loop for SettingPage, SettingGroup, and SettingTupleView.

ForEach(page.tuple.settings, id: \.identifier) { setting in
    SettingView(setting: setting, isPagePreview: true)
}

ForEach(group.tuple.settings, id: \.identifier) { setting in
    SettingView(setting: setting)
}

ForEach(tuple.settings, id: \.identifier) { setting in
    SettingView(setting: setting)
}

Looping over each element's children, for example `page.tuple.settings`

Currently, Setting synthesizes this ID depending on the element — for SettingText, it gets the title property. For SettingTupleView, it gets tuple.flattened.compactMap { $0.textIdentifier }.joined().

https://github.com/aheze/Setting/blob/main/Sources/Setting.swift#L18-L38

Ideally, we could get rid of this ID and just use a View's default identity. (For more details, see How the SwiftUI View Lifecycle and Identity work, "Identity of a view" section.)

No support for custom view modifiers

SettingToggle(title: "This value is persisted!", isOn: $isOn)
    .tint(.red) /// Argument type 'some View' does not conform to expected type 'Setting'

This requires changes to SettingBuilder.

The solution

SettingView needs to be generic, resembling SwiftUI's View as closely as possible.

If possible, we should make Setting conform to View, so that we can render it directly without the need for a huge switch.

I've attempted this and got lost quickly — I'm not good with generics.

Any help? :)

Icon support for SettingButton

I want to include a bunch of links at the bottom of my setting page and it would be nice if i could add an icon for these items to match the rest of them ☺️

Screenshot 2023-02-28 at 08 38 45

TextFields as SettingTextField

I really appreciate your work. It looks very nice native. But what would be even better would be if you could add text fields not only via a custom view, but that they would be like for example SettingButton SettingTextField. Thanks a lot!

SettingPicker duplicates values

iOS 17.2, Xcode 15.2

The SettingPicker seems to have a bug ( see video )

Simulator.Screen.Recording.-.iPhone.15.Pro.-.2024-02-14.at.17.00.19.mp4

Missing modifiers

Hey @aheze,
I wanted to let you know that I really like this framework, but I've noticed that some important modifiers are missing for your Toggles, specifically .disabled(disabled: Bool) and .onChange(of: perform:). It would also be nice if instead of using the @SettingBuilder macro to create a new settings view, you could just create a new view and link it to the SettingPage.

Unable to change Background Color for pushed SettingCustomView

SettingPage(title: "Integrations") {
                     SettingCustomView {
                                        IntegrationsSettingView()
                      }
}

I'm navigating User to Custom settings view where i want to change background color for that View including navigation area, but unable to set background color for entire screen. Attached is the screen shot for reference.
simulator_screenshot_C6E58EF5-27FC-4181-9C89-D3B8CCBEA60A

Any help would be greatly appreciated.

Navigate to UIKit

Let's say I had an existing UIViewController in my current settings that i don't want to recreate in SwiftUI, what's the best way of continuing to use it within this framework?

I've made a UIViewControllerRepresentable View and used it within a SettingCustomView, but it doesn't look like it sizes correctly e.g. has a 0 height, 0 width frame unless i set one manually. If i have to do that, is there a way to get the right height?

(ps. sorry for creating so many issues 🥺)

struct LibrarySectionsView: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> LibrarySectionOrderViewController {
        return LibrarySectionOrderViewController()
    }

    func updateUIViewController(_ uiViewController: LibrarySectionOrderViewController, context: Context) { }
}
SettingPage(title: "Library Sections") {
      SettingCustomView {
          LibrarySectionsView()
      }
  }

Conditionals do not behave as expected

Screen.Recording.2024-01-25.at.11.58.20.PM.mov
struct ContentView: View {
    @State var enableSecondGroup = false
    var body: some View {
        VStack {
            Button {
                enableSecondGroup.toggle()
            } label: {
                Text("Toggle Group 2")
            }
            SettingStack {
                SettingPage(title: "Playground") {
                    SettingGroup(header: "Group 1") {
                        SettingCustomView {
                            Text("Hello Group 1")
                        }
                    }

                    if enableSecondGroup {
                        SettingGroup(header: "Group 2") {
                            SettingCustomView {
                                Text("Hello Group 2")
                            }
                        }
                    }

                }
            }
        }
        .padding()
    }
}

Expected behavior

Group 1 should only be visible when the toggle is off; Group 1 and 2 should be visible when toggle is on

Actual behavior

Group 1 is visible when toggle is off; Group 2 is duplicated when toggle is on

Icon for SettingToggle

Is it possible to have a icon on SettingToggle in the same way that SettingPicker and SettingPage do?
I see you've created #23 that will allow for lots more composability of these views, but I just wanted to double check this wasn't already possible.

Thanks so much for making this btw, I know you're a young guy, and you've got tremendous amounts of talent! You've helped me have better Settings options more my users, and helped me to start implementing SwiftUI in my UIKit app 😊

Add opt-in usage of sidebar in NavigationStack/NavigationView

This is a fantastic library and just the thing I was looking for recently.

I am building a macOS app and I'm working on a refactor of Setting to allow the use of the sidebar as the top level, very much like how macOS Ventura's System Settings does:

macos-settings

It started as a small refactor (WIP) of the SettingExample project to use NavigationView with a sidebar instead of TabView:

setting-sidebar

But then I realized it would be much nicer if the sidebar was actually an opt-in feature of Setting. The reason is that right now, the text search function only searches within the scope of the current top-level item selected, not across all of them at once.

Additionally, in macOS Settings, the search bar is positioned within the sidebar (which doesn't really work on macOS) and its text search filters the sidebar contents during searching.

A question on initialization

Hey @aheze , Great package, Can wait to make a PR ✨

I just had a small question:

I've seen that in many places throughout the project, You're initializing structs with default argument value identical to the struct's properties' default values. I wanted to know if there's any particular reason for this?

public struct PreviewConfiguration {
    public var icon: SettingIcon?
    public var indicator = "chevron.forward"
    public var horizontalSpacing = CGFloat(12)
    public var verticalPadding = CGFloat(14)
    public var horizontalPadding = CGFloat(16)

    public init(
        icon: SettingIcon? = nil,
        indicator: String = "chevron.forward",
        horizontalSpacing: CGFloat = CGFloat(12),
        verticalPadding: CGFloat = CGFloat(14),
        horizontalPadding: CGFloat = CGFloat(16)
    ) {
        self.icon = icon
        self.indicator = indicator
        self.horizontalSpacing = horizontalSpacing
        self.verticalPadding = verticalPadding
        self.horizontalPadding = horizontalPadding
    }
}

In-line picker

Is it possible to use a SettingPicker but display it inline with other items?

for example:
IMG_3A0D7B2CD4CD-1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.