Giter Site home page Giter Site logo

avdlee / swiftuikitview Goto Github PK

View Code? Open in Web Editor NEW
742.0 13.0 24.0 84 KB

Easily use UIKit views in your SwiftUI applications. Create Xcode Previews for UIView elements

Home Page: https://www.avanderlee.com

License: MIT License

Swift 100.00%
swiftui uikit previews uiview uiviewrepresentable xcode

swiftuikitview's Introduction

SwiftUIKitView

Swift Version Dependency frameworks Twitter

Easily use UIKit views in SwiftUI.

  • Convert UIView to SwiftUI View
  • Create Xcode Previews from UIView elements
  • SwiftUI functional updating UIView properties using a protocol with Associated Types.

You can read more about Getting started with UIKit in SwiftUI and visa versa.

Examples

Using SwiftUIKitView in Production Code

Using a UIKit view directly in SwiftUI for production code requires you to use:

UIViewContainer(<YOUR UIKit View>, layout: <YOUR LAYOUT PREFERENCE>)

This is to prevent a UIKit view from being redrawn on every SwiftUI view redraw.

import SwiftUI
import SwiftUIKitView

struct SwiftUIwithUIKitView: View {
    var body: some View {
        NavigationView {
            UIViewContainer(UILabel(), layout: .intrinsic) // <- This can be any `UIKit` view.
                .set(\.text, to: "Hello, UIKit!") // <- Use key paths for updates.
                .set(\.backgroundColor, to: UIColor(named: "swiftlee_orange"))
                .fixedSize()
                .navigationTitle("Use UIKit in SwiftUI")
        }
    }
}

Using SwiftUIKitView in Previews

Performance in Previews is less important, it's being redrawn either way.

Therefore, you can use the more convenient swiftUIView() modifier:

UILabel() // <- This is a `UIKit` view.
    .swiftUIView(layout: .intrinsic) // <- This is returning a SwiftUI `View`.

Creating a preview provider for a UIView looks as follows:

import SwiftUI
import SwiftUIKitView

struct UILabelExample_Preview: PreviewProvider {
    static var previews: some View {
        UILabel() // <- This is a `UIKit` view.
            .swiftUIView(layout: .intrinsic) // <- This is a SwiftUI `View`.
            .set(\.text, to: "Hello, UIKit!") // <- Use key paths for updates.
            .fixedSize() // <- Make sure the size is set
            .previewLayout(.sizeThatFits)
            .previewDisplayName("UILabel Preview Example")
    }
}

Which results in the following preview:

KeyPath updating

This framework also comes with a KeyPathReferenceWritable protocol that allows to update objects using functions and writable KeyPath references:

/// Defines a type that is configurable using reference writeable keypaths.
public protocol KeyPathReferenceWritable {
    associatedtype T
    associatedtype U
    
    func set<Value>(_ keyPath: ReferenceWritableKeyPath<T, Value>, to value: Value) -> U
}

public extension KeyPathReferenceWritable {
    func set<Value>(_ keyPath: ReferenceWritableKeyPath<Self, Value>, to value: Value) -> Self {
        self[keyPath: keyPath] = value
        return self
    }
}

/// Add inheritance for NSObject types to make the methods accessible for many default types.
extension NSObject: KeyPathReferenceWritable { }

This can be used as follows:

UILabel()
    .set(\.text, to: "Example")

And allows to easily build up SwiftUI style view configurations to keep the same readability when working in SwiftUI.

Installation

Swift Package Manager

The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift compiler. It is in early development, but this SDK does support its use on supported platforms.

Once you have your Swift package set up, adding the SDK as a dependency is as easy as adding it to the dependencies value of your Package.swift.

dependencies: [
    .package(url: "https://github.com/AvdLee/SwiftUIKitView.git", .upToNextMajor(from: "2.0.0"))
]

Communication

  • If you found a bug, open an issue.
  • If you have a feature request, open an issue.
  • If you want to contribute, submit a pull request.

License

SwiftUIKitView is available under the MIT license, and uses source code from open source projects. See the LICENSE file for more info.

Author

This project is originally created by Antoine van der Lee. I'm open for contributions of any kind to make this project even better.

swiftuikitview's People

Contributors

avdlee avatar coledunsby 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

swiftuikitview's Issues

Update not working?

struct ContentView: View {
    @State var counter = 0
    
    var body: some View {
        VStack {
            
            Text("Hello no \(counter) from SwiftUI")
                .padding()
            
            UILabel() // <- This can be any `UIKit` view.
                .swiftUIView(layout: .intrinsic) // <- This is returning a SwiftUI `View`.
                .set(\.text, to: "Hello no \(self.counter) from UIKit") // <- Use key paths for updates.
                .fixedSize()
        }
        .onAppear {
            if counter == 0 {
                schedule()
            }
        }
    }
    
    func schedule() {
        counter += 1
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            self.schedule()
        }
    }
}

simulator_screenshot_581B71A7-9A1F-45C6-8F09-2E1AB04392C5

I expected the UILabel to be updated and behave like my SwiftUI Text-view, but instead it is showing just 0. Also, recreating the UILabel every time the view hierarchy is declared is not a good idea as it may happen many many times. I think this is a fundamental issue with the approach in this library. I find this approach better and easier

import SwiftUI
import UIKit

struct UIViewMaker<ViewType: UIView>: UIViewRepresentable {
    
    typealias UIViewType = ViewType
    
    var make: () -> ViewType = ViewType.init
    var update: (ViewType) -> ()
    
    func makeUIView(context: Context) -> ViewType {
        return make()
    }
    
    func updateUIView(_ uiView: ViewType, context: Context) {
        update(uiView)
    }
}

struct ContentView: View {
    @State var counter = 0
    
    var body: some View {
        VStack {
            
            Text("Hello no \(counter) from SwiftUI")
                .padding()
            
            
            UIViewMaker<UILabel> {
                $0.text = "Hello no \(self.counter) from UIKit"
            }
            .fixedSize()
            
        }
        .onAppear {
            if counter == 0 {
                schedule()
            }
        }
    }
    
    func schedule() {
        counter += 1
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            self.schedule()
        }
    }

}

`UILabel` Preview Example not working

UILabel Preview Example in project SwiftUIKitExample.xcodeproj does not work.

        UILabel() // <- This is a `UIKit` view.
            .swiftUIView(layout: .intrinsic) // <- This is a SwiftUI `View`.
            .set(\.text, to: "Hello, UIKit!") // <- Use key paths for updates.
            .fixedSize() // <- Make sure the size is set
            .previewLayout(.sizeThatFits)
            .previewDisplayName("UILabel Preview Example")
    }

Expected to see the text "Hello, UIKit!" but that text is not visible in the preview :(

Screen.Recording.2022-10-04.at.11.43.59.AM.mov

Tested with Xcode 14.0.1 and iPhone 13 (iOS 16) simulator

Question on UIActivityIndicatorView compatibility

Hi, I have tried the library it is very perfectly if I am adding an UILabel or UIView. But now I am trying to add UIActivityIndicatorView, seems it doesn't work. Is this syntax below correct ?. I tried this but the view is not showing anything, but once I try with UILabel or UIView, it works fine.

UIActivityIndicatorView(style: .large)
                .swiftUIView(layout: .fixed(size: CGSize(width: 100, height: 100)))
                .set(\.color, to: UIColor.blue)
                .set(\.isHidden, to: false)
                .fixedSize()

second question, how did I trigger a function that preserved from one of the subclass of UIView ? Let say this activity indicator has an open function called as startAnimating(). however I can't using the declarative syntax in above code, is it expected to only set a value but can't call any derived method ?

Thank you before, @AvdLee

Action isn't being called?

public struct ContentView: View {
        var body: some View {
                return AnyView(
                        ViewController().view
                                .swiftUIView(layout: .intrinsic)
                )
        }
}

class ViewController: UIViewController {
	
	var scrollView = UIScrollView()
	let contentView = UIView()
	var pullControl = UIRefreshControl()
	
	override func viewDidLoad() {
		super.viewDidLoad()
		
		setupScrollView()
		setupViews()
	}
	
	@objc func handleRefreshControl() {
		// Update your content…
		print("hi")
		// Dismiss the refresh control.
		DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
			self.scrollView.refreshControl?.endRefreshing()
		}
	}
	
	func setupScrollView(){
		scrollView.translatesAutoresizingMaskIntoConstraints = false
		contentView.translatesAutoresizingMaskIntoConstraints = false
		
		view.addSubview(scrollView)
		scrollView.addSubview(contentView)
		
		scrollView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
		scrollView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
		scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
		scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
		scrollView.backgroundColor = UIColor.red
		
		scrollView.refreshControl = pullControl
		
		
		scrollView.refreshControl?.addTarget(self, action:
												#selector(handleRefreshControl),
											 for: .valueChanged)
		
		
		contentView.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor).isActive = true
		contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true
		contentView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
		contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
	}
	
	func setupViews(){
		child.view.sizeToFit()
		child.view.translatesAutoresizingMaskIntoConstraints = false
		contentView.addSubview(child.view)
		child.view.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
		child.view.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
		child.view.widthAnchor.constraint(equalTo: contentView.widthAnchor).isActive = true
		child.view.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
	}
	
	let child: UIHostingController = UIHostingController(rootView: TestView())
}

public struct TestView : View {
	public var body: some View {
		VStack {
			Group {
				Text("Test1")
				Text("Test2")
				Text("Test3")
				Text("Test4")
				Text("Test5")
				Text("Test6")
				Text("Test7")
				Text("Test8")
				Text("Test9")
				Text("Test10")
			}
		}
	}
}

When I swipe to refresh, refreshData isn't being called. The refresh animation plays endlessly. However, my code works when it isn't embedded in a SwiftUI view. Is this issue fixable?

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.