GithubHelp home page GithubHelp logo

swiftuix / swiftuix Goto Github PK

View Code? Open in Web Editor NEW
6.6K 72.0 403.0 3.38 MB

An exhaustive expansion of the standard SwiftUI library.

License: MIT License

Swift 99.95% Ruby 0.05%
swift-package-manager textview swift macos swiftui attributedstring framework library scroll backwards-compatibility

swiftuix's Introduction

SwiftUIX

CI

SwiftUIX attempts to fill the gaps of SwiftUI, providing an extensive suite of components, extensions and utilities to complement the standard library. This project is by far the most complete port of missing UIKit/AppKit functionality, striving to deliver it in the most Apple-like fashion possible.

Why

The goal of this project is to complement the SwiftUI standard library, offering hundreds of extensions and views that empower you, the developer, to build applications with the ease promised by the revolution that is SwiftUI.

Requirements

Note

Swift 5.9 is the latest release for Swift and adds support for macros, support for Swift 5.8 will be dropped soon.

  • Deployment target: iOS 13, macOS 10.15, tvOS 13, watchOS 6 and visionOS 1 beta 6 (Xcode Xcode 15.1 beta 3)
  • Xcode 15.0+

Installation

The preferred way of installing SwiftUIX is via the Swift Package Manager.

/// Package.swift
/// ...
dependencies: [
    .package(url: "https://github.com/SwiftUIX/SwiftUIX.git", branch: "master"),
]
/// ...

Xcode 15 integrates with libSwiftPM to provide support for iOS, watchOS, macOS and tvOS platforms.

  1. In Xcode, open your project and navigate to FileSwift PackagesAdd Package Dependency...
  2. Paste the repository URL (https://github.com/SwiftUIX/SwiftUIX) and click Next.
  3. For Rules, select Branch (with branch set to master).
  4. Click Finish.
  5. Open the Project settings, add SwiftUI.framework to the Linked Frameworks and Libraries, set Status to Optional.

Contents

All documentation is available via the repository wiki.

While the project itself is stable and heavily being used in production, its documentation is work-in-progress. Contributions are encouraged and welcomed.

UIKit → SwiftUI

UIKit SwiftUI SwiftUIX
LPLinkView - LinkPresentationView
UIActivityIndicatorView - ActivityIndicator
UIActivityViewController - AppActivityView
UIBlurEffect - BlurEffectView
UICollectionView - CollectionView
UIDeviceOrientation - DeviceLayoutOrientation
UIImagePickerController - ImagePicker
UIPageViewController - PaginationView
UIScreen - Screen
UISearchBar - SearchBar
UIScrollView ScrollView CocoaScrollView
UISwipeGestureRecognizer - SwipeGestureOverlay
UITableView List CocoaList
UITextField TextField CocoaTextField
UIModalPresentationStyle - ModalPresentationStyle
UIViewControllerTransitioningDelegate - UIHostingControllerTransitioningDelegate
UIVisualEffectView - VisualEffectView
UIWindow - WindowOverlay

Activity

  • ActivityIndicator

    ActivityIndicator()
        .animated(true)
        .style(.large)
    
  • AppActivityView - a SwiftUI port for UIActivityViewController.

    AppActivityView(activityItems: [...])
        .excludeActivityTypes([...])
        .onCancel { }
        .onComplete { result in
            foo(result)
        }

Appearance

  • View/visible(_:) - Sets a view's visibility.

CollectionView

Use CollectionView within your SwiftUI view, providing it with a data source and a way to build cells.

import SwiftUIX

struct MyCollectionView: View {
    let data: [MyModel] // Your data source

    var body: some View {
        CollectionView(data, id: \.self) { item in
            // Build your cell view
            Text(item.title)
        }
    }
}

Error Handling

  • TryButton - A button capable of performing throwing functions.

Geometry

  • flip3D(_:axis:reverse:) - Flips this view.
  • RectangleCorner - A corner of a Rectangle.
  • ZeroSizeView - A zero-size view for when EmptyView just doesn't work.

Keyboard

  • Keyboard - An object representing the keyboard.
  • View/padding(.keyboard) - Pads this view with the active system height of the keyboard.

Link Presentation:

Use LinkPresentationView to display a link preview for a given URL.

LinkPresentationView(url: url)
    .frame(height: 192)

Navigation Bar

  • View/navigationBarColor(_:) - Configures the color of the navigation bar for this view.
  • View/navigationBarTranslucent(_:) - Configures the translucency of the navigation bar for this view.
  • View/navigationBarTransparent(_:) - Configures the transparency of the navigation bar for this view.
  • View/navigationBarLargeTitle(_:) - Set a custom view for the navigation bar's large view mode.

Pagination

  • PaginationView

    PaginationView(axis: .horizontal) {
        ForEach(0..<10, id: \.hashValue) { index in
            Text(String(index))
        }
    }
    .currentPageIndex($...)
    .pageIndicatorAlignment(...)
    .pageIndicatorTintColor(...)
    .currentPageIndicatorTintColor(...)

Scrolling

  • View/isScrollEnabled(_:) - Adds a condition that controls whether users can scroll within this view. Works with:

    • CocoaList
    • CocoaScrollView
    • CollectionView
    • TextView

    Does not work with SwiftUI's ScrollView.

Search

  • SearchBar - A SwiftUI port for UISearchBar.

    struct ContentView: View {
        @State var isEditing: Bool = false
        @State var searchText: String = ""
    
        var body: some View {
            SearchBar("Search...", text: $searchText, isEditing: $isEditing)
                .showsCancelButton(isEditing)
                .onCancel { print("Canceled!") }
        }
    }
  • View/navigationSearchBar(_:) - Sets the navigation search bar for this view.

    Text("Hello, world!")
        .navigationSearchBar {
            SearchBar("Placeholder", text: $text)
        }
  • View/navigationSearchBarHiddenWhenScrolling(_:) - Hides the integrated search bar when scrolling any underlying content.

Screen

  • Screen - A representation of the device's screen.
  • UserInterfaceIdiom - A SwiftUI port for UIUserInterfaceIdiom.
  • UserInterfaceOrientation - A SwiftUI port for UserInterfaceOrientation.

Scroll

  • ScrollIndicatorStyle - A type that specifies the appearance and interaction of all scroll indicators within a view hierarchy
    • HiddenScrollViewIndicatorStyle - A scroll indicator style that hides all scroll view indicators within a view hierarchy.

Status Bar

  • View/statusItem(id:image:) - Adds a status bar item configured to present a popover when clicked

    Text("Hello, world!")
        .statusItem(id: "foo", image: .system(.exclamationmark)) {
            Text("Popover!")
                .padding()
        }

Text

  • TextView

    TextView("placeholder text", text: $text, onEditingChanged: { editing in
        print(editing)
    })

Visual Effects

  • VisualEffectBlurView - A blur effect view that expands to fill.

    VisualEffectBlurView(blurStyle: .dark)
        .edgesIgnoringSafeArea(.all)

Window

  • View/windowOverlay(isKeyAndVisible:content:) - Makes a window key and visible when a given condition is true.

Contributing

SwiftUIX welcomes contributions in the form of GitHub issues and pull-requests. Please refer the projects section before raising a bug or feature request, as it may already be under progress.

To create an Xcode project for SwiftUIX run bundle install; bundle exec fastlane generate_xcodeproj. To check the automated builds for SwiftUIX run bundle install; bundle exec fastlane build.

License

SwiftUIX is licensed under the MIT License.

Support

SwiftUIX is and will always remain free and open-source.

Maintaining SwiftUIX is a massively time-consuming endeavour. If you're reliant on SwiftUIX for your app/project and would like to see it grow, consider either:

Credits

SwiftUIX is led and maintained by @vatsal_manot.

Special thanks to Brett Best, Nathan Tanner, Kabir Oberai and many more.

swiftuix's People

Contributors

adarovsky avatar benlmyers avatar brett-best avatar coledunsby avatar dadalar avatar dscyrescotti avatar emmavvv avatar fampayyc avatar hstdt avatar iaugux avatar ihtcboy avatar jevonmao avatar lorenzofiamingo avatar mlch911 avatar moriquendi avatar mufasayc avatar naeemshaikh90 avatar overcot avatar paulofaria avatar siddarthgandhi avatar steipete avatar tareksabry1337 avatar touyu avatar traleven avatar vicky-ghost avatar vmanot avatar woxtu avatar yosshi4486 avatar zeveisenberg avatar zsy78191 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  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

swiftuix's Issues

NavigationBar custom View gesture bug

.navigationBarTitleView(
HStack {
    Text(title)
    Image(systemName: "chevron.down")
}.onTapGesture {
    self.isPopUpPresented = true
}
, displayMode: .inline)

When I click first time on the label, pop-up is presented. Inside pop-up I select the option which changes title state and closes itself, after that title view stops responding to tap gestures.

contentOffset doesn't work for CocoaList

Contentoffset works very well under CocoaScrollView.
But it doesn't work under CocoaList.

import SwiftUI
import SwiftUIX

struct CocoaListBugReport: View {
    var listData = (0...300).map{Item(title: String($0))}
    var body: some View {
        CocoaList(listData){ item in
            Text(item.title)
        }
        .contentOffset(.constant(CGPoint(x:0,y:400)))
    }
}

struct CocoaListBugReport_Previews: PreviewProvider {
    static var previews: some View {
        CocoaListBugReport()
    }
}

struct Item: Identifiable {
  var id = UUID()
  var title: String
}

TextView moves cursor to the end after return key

In TextView, pressing return key twice, moves the cursor to the bottom of the TextView. Which makes it unusable. Any ideas how to fix it?

On XCode 11.3.1. In simulator and on device. Try it with this trivial code. Run it and type in: return key, some text, scroll the cursor to the top, return key.

import SwiftUI
import SwiftUIX

struct ContentView: View {
    @State private var text = ""
    
    var body: some View {
            TextView("type in", text: $text)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Crashed when using isIntialFirstResponder on CocoaTextField

Environment

  • master branch
  • Xcode11.4 beta4
  • CocoaTextField.swift

Problem

Crashed when using isIntialFirstResponder(true) modifier.

スクリーンショット 2020-03-16 13 31 16

eg)
SomeView
.sheet(isPresented: $isPresented) {
    CocoaTextField("", text: self.$text)
        .isInitialFirstResponder(true)
}

Why

Calling becomeFirstResponder() -> Bool may cause crash before adding the view to view hierarchy as described in this apple document.: (https://developer.apple.com/documentation/uikit/uiresponder/1621113-becomefirstresponder)

I suppose SwiftUI doesn't change view hierarchy while it is in makeUIView step. so, Calling becomeFirstResponder() in makeUIView cause crash.

Workaround

Use DispatchQueue.main.async to delay executing becomeFirstResponder(). updateUIView() doesn't occur crash, so I suppose SwiftUI add view to view hierarchy just after makeUIView().

before

public func makeUIView(context: Context) -> UIViewType {
        let uiView = _UITextField()
        
        uiView.delegate = context.coordinator
        
        if let isFirstResponder = isInitialFirstResponder, isFirstResponder {
                uiView.becomeFirstResponder()
        }
        
        return uiView
    }

after

public func makeUIView(context: Context) -> UIViewType {
        let uiView = _UITextField()
        
        uiView.delegate = context.coordinator
        
        if let isFirstResponder = isInitialFirstResponder, isFirstResponder {
            
            DispatchQueue.main.async {
                uiView.becomeFirstResponder()
            }
        }
        
        return uiView
    }

PaginationView and currentPageIndex

Further to my recent PaginationView issue I would like to get the current page number, but can't see a way of achieving this. Is there one?

ImagePicker

It would be nice if you could #add the option to choose the SourceType on the interface rather than hardwire it to .photoLibrary.

BTW You haven't responded to my comment on issue #66 (which you had closed).

[Bug] Not correctly reload button in navigation bar

Hi,
I use your library. Thanks for your work.
I have a problem.
In my app I set the bar ButtonItems like this

NavigationView {
MyView(vM: .init()).navigationBarItems(leading: self.LeadingButton(), center: self.NavbarImage(),
                                                            trailing: self.TrailingButton(), displayMode: .inline)
}

However, sometimes I need to hide/modify the barbuttons I show to the user.
So, there is a @published variable in the model of the Main View that change if the user make specific action.

Here the problem:
the buttons are not update, it still show the old ones.
I try to use the native method of SwiftUI (without center and displayMode) and it works fine the buttons update, so I guess the problem is a missing refresh. What can I do?

No such module 'Merge'

I get this error since trying to update the Swift Package from revision 89d980c4db9c636bed505a3df9e64f4287881777 to 6ac261ace4a5b20bdbe16deebfdacf9fe274329a.

Present sheet with Clear Background

I needed to present a modal sheet with clear background. I'm using now this workaround:

extension UIViewController {
    func present<Content: View>(presentationStyle: UIModalPresentationStyle = .automatic, transitionStyle: UIModalTransitionStyle = .coverVertical, clearBackground: Bool = false, animated flag: Bool = true, completion: @escaping () -> Void = {}, @ViewBuilder builder: () -> Content) {
        let toPresent = UIHostingController(rootView: AnyView(EmptyView()))
        toPresent.modalPresentationStyle = presentationStyle
        toPresent.modalTransitionStyle = transitionStyle
        toPresent.rootView = AnyView(
            builder()
//                .environment(\.viewController, ViewControllerHolder(toPresent))
        )
        if clearBackground  {
            toPresent.view.backgroundColor = .clear
        }
        self.present(toPresent, animated: flag, completion: completion)
    }
}

and using it with:

UIApplication.shared.windows.first?.rootViewController?.present(...)

There is the possibility to implement this like for View+navigate, (View+present)?

Checkbox images

I think it's more intuitive if the checkbox used an empty square image when off ("square" instead of "checkmark.square").

When we have multiple checkboxes and none of them is on, it feels like they're all checked by default.

Can you please update or give us the option to choose which symbol to use?

Captura de ecrã 2020-04-27, às 17 45 07

Navigating a Page Control

I have used PaginationControl with a ForEach view. I would like to add control buttons to navigate between views. Is this possible, and if it is, how?

[Bug] NavigationBar size at start

Hi,

I have a simple problem: my app when start the navigation bar has the wrong size (expanded and not inline), after a simple refresh the navigationBar change to the correct size, but it is pretty ugly.
If i put an empty navigationTitle the size is correct, but it seems a bit hackish (or maybe is the correct way? I am not very skilled about SwiftUI)
Here a snippet to show what I mean:

MyView(viewModel:.init())
                       .navigationBarTitle("", displayMode: .inline) //need this line to show as inline at start
                       .navigationBarItems(leading: EmptyView(), center: NavbarLogoImage(),
                                                          trailing: EmptyView(), displayMode: .inline)

PaginationView doesn't show

Hi,
it seems that PaginationView doesn't show in the main view where I place it. See a couple of examples of what I tried below.

ScrollView(.vertical) {
        
            VStack(alignment: .leading) {

                ExerciseMediaPaginatedHeader(exercise: self.exercise)
            

                .... other views

}
}

This doesn't show inside the Scroll view above:

struct ExerciseMediaPaginatedHeader: View {

let exercise:Exercise
  
  var body: some View {
    PaginationView(axis: Axis.horizontal) {

        Text("bla")
        Text("blup")
        Text("foo")
    }
  }

}

Pagination view also does not show in the scroll view above if I add more complex views:

struct ExerciseMediaPaginatedHeader: View {

let exercise:Exercise
  
  var body: some View {
    PaginationView(axis: Axis.horizontal) {
        
        self.getViews()
    }
  }

func getViews()->[AnyView] {
    
    var views: [AnyView] = [VideoZStackView(storagePath: self.exercise.videoStoragePath).eraseToAnyView()]
    self.exercise.imageStoragePaths.forEach { (path) in
        let firebaseImageView = FirebaseImage(storagePath: path).frame(width: CGFloat(UIScreen.main.bounds.width  - CGFloat(20)), height: CGFloat(UIScreen.main.bounds.width - 20) / CGFloat(1.78), alignment: .center).aspectRatio(contentMode: .fill).eraseToAnyView()
        views.append(firebaseImageView)
    }
    return views
}

}

When adding more complex views without using the getViews func above , the swift compiler thows some BS SwiftUI-style fake errors that we all love:

  var body: some View {
    PaginationView(axis: Axis.horizontal) {
        
        VideoZStackView(storagePath: self.exercise.videoStoragePath).eraseToAnyView()

        FirebaseImage(storagePath: self.exercise.imageStoragePaths.first!).frame(width: CGFloat(UIScreen.main.bounds.width  - CGFloat(20)), height: CGFloat(UIScreen.main.bounds.width - CGFloat(20)) / CGFloat(1.78), alignment: .center).aspectRatio(contentMode: .fill).eraseToAnyView()

// 'fake' compiler error: "Binary operator / cannot be applied to types Int and Double" . But I used this views within other views before and there was no error.
}
}

thanks for looking into this.

regards
Dominik

PaginationView index

Hi, great library!
Currently when updating the PaginationView index programmatically with currentPageIndex the page control dots don't change and also get out of sync with the index if you switch to swiping

Can't load dynamic data inside PaginationView

I have to display some data from api. This is the code:

PaginationView(axis: .horizontal) {

                ForEach(self.banners, id: \.id) { item in
               
URLImage(URL(string:"exampleurl")!)
                    { proxy in
                        proxy.image
                            .resizable()
                    }.frame(width: UIScreen.main.bounds.width - 120, height: 200).aspectRatio(contentMode: .fit)
                        .cornerRadius(15)

                }
                
            }.onAppear(perform: loadData)

Everything I put inside foreach, even if I put static data it says Cannot convert value of type 'ForEach<[Banner], Int, some View>' to closure result type 'Array'.
How can I load data with foreach inside PaginationView?

What is the need of @State private var isPresented?

In PresentationLink.swift, what is the use of @State private var isPresented? It is never read.
It is never used.

public struct PresentationLink<Destination: View, Label: View>: View {
    public let destination: Destination
    public let label: Label

    private let onDismiss: (() -> ())?

    public init(destination: Destination, onDismiss: (() -> ())? = nil, @ViewBuilder label: () -> Label) {
        self.destination = destination
        self.label = label()
        self.onDismiss = onDismiss
    }

    public var body: some View {
    Button(action: nil, label: { label })
    .sheet(
    onDismiss: dismiss,
    content: { self.destination }
    )
    }

    private func dismiss() {
        onDismiss?()
    }
}

Segmentation Fault 11 on archive using Xcode 11.4

import SwiftUIX

struct MyButtonStyle: ButtonStyle {
  func makeBody(configuration: Configuration) -> some View {
    configuration.label
  }
}

struct ContentView: View {

  var body: some View {
    Button("My Button", action: {})
      .buttonStyle(MyButtonStyle())
      .fill()
  }
  
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
      .fill()
  }
}

Using Xcode 11.4, create a blank project (add SPM SwiftUIX) and use the above code snippet for the content view.
Attempt to archive the project for release, a segmentation fault 11 should be produced.

The following tweets might be helpful, as well as the two commits linked.
https://twitter.com/codeslice/status/1247141849531326465?s=21
https://twitter.com/codeslice/status/1247142251861618695?s=21

Entire thread: https://twitter.com/brettbestaus/status/1242648289742225408?s=20

CodeSlicing/pure-swift-ui@4fb6f29
CodeSlicing/pure-swift-ui@0a242ff

[Question] How to set large title view?

I tried to use navigationBarTitleView(_: displayMode) to add a

NavigationView {
                List(emojiList, id: \.self) {
                    Text($0)
                }.navigationBarTitleView(
                    VStack {
                        Text("My Title")
                        Text("My sub-title").font(.subheadline)
                    }.height(84).width(200),
                    displayMode: .large
                )
            }.tabItem {
                Image(systemName: "star")
            }

However, it seems that the LargeTitle is not set, and only the view in the centre is set, which would be the behaviour after the user had scrolled -- so the large title would be collapsed.

Is there a way of setting a large title view that will collapse?

Refs

[How can I add a custom view on the large title view of UINavigationBar introduced in iOS11](https://stackoverflow.com/questions/46620068/how-can-i-add-a-custom-view-on-the-large-title-view-of-uinavigationbar-introduce

Custom title view as large title in iOS 11 new navigation bar

Create docs branch so I can open a PR? =D

Hi, I thought the project would eventually need a docs page if it continues to grow (as opposed to having a giant README hehe), so I started one.

However, I don't have anywhere to create a PR to (I used a new docs branch). Could you create this empty branch so I can send a PR? =)

More Documentation/Example usage

Great library. I know it's work in progress but would love to see more documentation and example usage of components.

Keep up the good work.

Activity Indicator Crash

On iOS 13.0 I’m getting a crash:
Fatal error: Reading Environment<Optional> outside View.body: file
When accessing the uiView.color = tintColor?.toUIColor()

On iOS 13.1+, no crash is caused.

A workaround could be to disable tint color on iOS 13.0 only?

Setting CocoaList's contentOffset

I'd like to save the scroll offset of a CocoaList while navigating through pages.

I thought it was possible by using the onOffsetChange modifier, but the exposed ScrollView<AnyView>.ContentOffset argument doesn't let you get the contentOffset property as it seems to be declared as fileprivate.
I've tried creating a extension CocoaList with a custom method to get it, but the compiler tells me that the property is set as internal.

Also, I'd like to set the contentOffset back to where it was after navigating towards a page, but it seems there is no public setContentOffset: there's one in UIHostingTableViewController, but it isn't accessible.

Is there a way to currently do the things above?

Thanks in advance for any clarification.

The content in CocoaScrollView is not displayed.

The content in CocoaScrollView is not displayed.
I'm using the latest version

struct Test: View {
  var body: some View {
      CocoaScrollView {
        VStack {
          ForEach(0..<200) { i in
            Text(String(i))
              .foregroundColor(.black)
          }
        }
      }
    }
}

TextView holding reference to NSView

Hi - great module; thanks for it! :)

I'm running into a weird issue with TextView running on macOS on a master/detail view: When there's a TextView in the detail view, the contents of the TextView continue to show (and edit) the first item selected in the list view, even though the rest of the detail view has changed.

Gif of the issue: https://www.dropbox.com/s/2cp6upj7twfi601/TextView.gif

To set up to reproduce:

  • Make a new project in Xcode, e.g. "TextViewTest", selecting macOS > App and checking the box to use SwiftUI. Deselect Core Data, CloudKit, tests, etc.
  • Go to File > Swift Packages > Add Package Dependency and add SwiftUIX
  • Copy/Paste the code below to replace what's in ContentView.swift

To reproduce:

  • Build and run the app
  • Click on one of the items in the list on the left
  • Enter a note on the right
  • Click on one of the other items in the list of the left

Expected result:

  • The detail on the right should update to show the new selection's name (e.g. "Fish") and the placeholder text to enter a new note

Actual result:

  • The detail on the right updates the name, but the previously entered note remains.

Notes:

  • The note is still editing the note property of the original object.
  • If you click outside of one of the options (that is, select no option), then click an option again, TextView shows that option's note field (and will persist to until you select nothing again).
  • I'm not working on a meal selection app, I'm just hungry. ;-)
    import SwiftUIX

    struct ContentView: View {
        @State var selection: UUID?

        var meals = [
            Meal(name: "Fish"),
            Meal(name: "Steak"),
            Meal(name: "Chicken")
        ]

        var selectedMeal: Meal? {
            meals.first(where: {$0.id == selection})
        }

        var body: some View {
            HStack {
                List(selection: $selection) {
                    ForEach(meals) { meal in
                        Text(meal.name).tag(meal.id)
                    }
                }

                if selectedMeal != nil {
                    DetailView(meal: selectedMeal!)
                }
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
        }
    }

    struct DetailView: View {
        @ObservedObject var meal: Meal

        var body: some View {
            VStack(alignment: .leading) {
                Text("Meal: \(meal.name)")
                TextView("Enter some notes", text: $meal.note)
            }

        }
    }

    class Meal: Identifiable, ObservableObject, Hashable {
        static func == (lhs: Meal, rhs: Meal) -> Bool {
            lhs.id == rhs.id
        }

        func hash(into hasher: inout Hasher) {
            hasher.combine(id)
        }

        var id = UUID()
        var name: String = ""
        var note: String = ""

        init(name: String) {
            self.name = name
        }
    }

    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView()
        }
    }

ObservedPublisher for CurrentValueSubject

ObservedPublisher is a great solution that combines @State and onRecevie into one. But when using CurrentValueSubject there is a problem, ObservedPublisher ignores dropping the first value.
I added a line to the code and now it adapts nicely to CurrentValueSubject.

self._subscription = .init(initialValue: publisher
       .delay(for: .nanoseconds(1), scheduler: RunLoop.main)
       .sink(receiveValue: {
            updateWrappedValue.value($0)
        }))

CocoaTextField Bug

CocoaTextField(text: $text, label: {Text("name:")})
        .placeholder("hello")

after using .placeholder , the app will crush.

And I have another question, how do I change the color of TextField's input text ?
I can't use .foregroundColor(.red) to do it.

TextView modifiers don't work as expected

Hi, great library but TextView doesn't work as expected. It seems onCommit is never executed.
The modifier font seems to work but foreground color, keyboard type and line limit don't seem to work either. I don't know how the keyboard can resign either.
Thanks for looking int this.

    TextView("Notes", text: self.$workoutManager.workout.notes, onCommit: {
        /// is never executed. 
         UIApplication.shared.windows[0].endEditing(true)
        
    }).font(.footnote).foregroundColor(.blue).keyboardType(.decimalPad).lineLimit(4)

CocoaList initialContentAlignment issue

I have noticed an issue with current CocoaList initialContentAlignment implementation.
The issue seems to be in UIHostingTableViewController.correctContentOffset function.
This function is called whenever content size is updated by the observe value function in the event a view is added to the data source.
The issue here is the oldContentSize value: observeValue seems to be called multiple times with values like:

  1. old: 642 new: 452 (discarded by correctContentOffset: more on that later)
  2. old: 452 new: 722 (accepted by correctContentOffset)

You seem to have noticed this in correctContentOffset:

guard oldContentSize.maximumDimensionLength < newContentSize.maximumDimensionLength else {
    return
}

You then calculate the offset like this:

if initialContentAlignment.vertical == .bottom {
      newContentOffset.y += newContentSize.height - oldContentSize.height
}

but the delta is way higher than it should be (722-452 instead of 722-642) resulting in a wrong content offset.

If you remove the said guard the delta would be correct, but the offset will be set even when tableView.frame.size.height < newContentSize.height causing the view to be scrolled to bottom even when the content is not filling the whole frame.
You can't even guard on that condition because the condition could match the second call from observeValue and not the first one.

I'm new to UIKit and I have no idea why it's behaving like that.
I'm looking forward to hear your opinion on that.
Thanks.

PaginationView set currentPageIndex

Hello, I have a Binding like this: .currentPageIndex(self.$currentImageIndex)

When I set a new value for the currentImageIndex, the PaginationView changes to the correct page, but the pagination dots don't change.
Do I need to keep them in sync manually or is it a possible bug?

Build errors in watchOS and tvOS

watchOS
This error came up where you were calling an extension to AppKitOrUIKitHostingControllerProtocol. I noticed that most of the file is hidden from watchOS, except for this extension, though. You can probably solve this by hiding the extension from watchOS.

#if !os(watchOS) // Add this
extension AppKitOrUIKitHostingControllerProtocol {
    // ...
}
#endif // And this

tvOS
This one came up at if base?.isPagingEnabled ?? false (Under _UIHostingScrollViewRootView).

Errors
watchOS

.../Sources/Intermodular/Helpers/AppKit or UIKit/AppKitOrUIKitHostingControllerProtocol.swift:38:11: Use of undeclared type 'AppKitOrUIKitHostingControllerProtocol'

tvOS

.../Sources/Intermodular/Helpers/UIKit/UIHostingScrollView.swift:192:22: 'isPagingEnabled' is unavailable in tvOS

Navigation Bar size

Screen Shot 2020-05-11 at 01 12 52

The content is not available to place on its place. the view is giving extra space

PaginationView & ProgressionController

Following your suggestion in #66 I have tried using prevButton etc within a PaginationView content with @Environment(.progressionController) var progressionController. When the code is executed the progessionController value is nil. I can see that it is set privately in the controller code, but it doesn't seem to expose it publicly. What am I missing?

PaginationView PageControl not showing when alignment is set to .horizontal

There is an issue inside PaginationView.init where it is always ignoring the passed pageIndicatorAlignment argument (assuming it is always nil is wrong). Also I don't understand this check if axis == .vertical || pageIndicatorAlignment != .center { ... } inside PaginationView.body. The PageControl isn't showing when the alignment is horizontal. The check has to be removed and the paddings have to be corrected to account for all pageIndicatorAlignment cases.

PaginationView auto height

Is there a way to detect the height of the tallest view inside the PaginationView and make it its frame height?
Also, is it possible to make an "Auto Play" so it behaves like a slideshow?

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.