No Public API in SwiftUI to response for the resizable modifier of View protocol. Only Image in SwiftUI could work with .resizable(). Custom UIView like UIView for GIF is not resizable now.
I use SDWebImageSwiftUI AnimatedImage, which is backing UIKit View SDAnimatedImageView. AnimatedImage is not response to .resizable(), .scaleToFit, .aspectRatio(contentMode: .fit), etc. WebImage is backing SwiftUI Image, so it's working fine.
import SwiftUI
import SDWebImageSwiftUI
struct ContentView: View {
let url = URL(string: "https://media.giphy.com/media/H62DGtBRwgbrxWXh6t/giphy.gif")!
var body: some View {
VStack {
AnimatedImage(url: url)
.scaledToFit()
.frame(width: 100, height: 100)
WebImage(url: url)
.scaledToFit()
.frame(width: 100, height: 100)
}
}
}
Not sure if it's an Apple bug. Expect custom view like SDWebImageSwiftUI AnimatedImage is responsive to SwiftUI size related modifiers like .scaledToFit().
Related issue: https://github.com/SDWebImage/SDWebImageSwiftUI/issues/3
SwiftUI uses the compression resistance priority and the content hugging priority to decide what resizing is possible.
If you want to resize a view below its intrinsic content size, you need to reduce the compression resistance priority.
Example:
func makeUIView(context: Context) -> UIView {
let imageView = UIImageView(image: UIImage(named: "yourImage")!)
imageView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
imageView.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
return imageView
}
This will allow you to set .frame(width:height:) to any size you want.
Finally found a solution.
Make a UIView wrapper outside of the SDAnimationImageView or UIImageView, then override layoutSubviews() set the frame of subview.
Here is full code by me.
And SDWebImageSwiftUI also release a new version which uses wrapper to solve this problem.
class ImageModel: ObservableObject {
#Published var url: URL?
#Published var contentMode: UIView.ContentMode = .scaleAspectFill
}
struct WebImage: UIViewRepresentable {
#ObservedObject var imageModel = ImageModel()
func makeUIView(context: UIViewRepresentableContext<WebImage>) -> ImageView {
let uiView = ImageView(imageModel: imageModel)
return uiView
}
func updateUIView(_ uiView: ImageView, context: UIViewRepresentableContext<WebImage>) {
uiView.imageView.sd_setImage(with: imageModel.url)
uiView.imageView.contentMode = imageModel.contentMode
}
func url(_ url: URL?) -> Self {
imageModel.url = url
return self
}
func scaledToFit() -> Self {
imageModel.contentMode = .scaleAspectFit
return self
}
func scaledToFill() -> Self {
imageModel.contentMode = .scaleAspectFill
return self
}
}
class ImageView: UIView {
let imageView = UIImageView()
init(imageModel: ImageModel) {
super.init(frame: .zero)
addSubview(imageView)
}
override func layoutSubviews() {
super.layoutSubviews()
imageView.frame = bounds
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Related
I'm currently using UIKit for making views and now I want to preview it just like SwiftUI.
But my canvas preview looks like a device rather than the size of view itself.
What have I done wrong?
import UIKit
class MyYellowButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder: NSCoder) {
fatalError("not support coder")
}
// MARK: - Private
private func setupView() {
backgroundColor = .yellow
setTitleColor(.black, for: .normal)
}
}
#if canImport(SwiftUI) && DEBUG
import SwiftUI
struct UIViewPreview<View: UIView>: UIViewRepresentable {
let view: View
init(_ builder: #escaping () -> View) {
view = builder()
}
// MARK: - UIViewRepresentable
func makeUIView(context: Context) -> UIView {
return view
}
func updateUIView(_ view: UIView, context: Context) {
view.setContentHuggingPriority(.defaultHigh, for: .horizontal)
view.setContentHuggingPriority(.defaultHigh, for: .vertical)
}
}
struct MyYellowButtonPreview: PreviewProvider{
static var previews: some View {
UIViewPreview {
let button = MyYellowButton(frame: .zero)
button.setTitle("buttonTest", for: .normal)
return button
}.previewLayout(.sizeThatFits)
}
}
#endif
I wanted my preview to look like this
'.sizeThatFits' and '.fixed' arguments used by 'previewLayout' modifier display container view without device bezels and safe-area insets in selectable mode. In 'Live' mode, a view is always displayed as a device with bezels.
I want to implement UIScrollView in UIKit using UIViewRepresentable in SwiftUI.
But I have a problem that UIScrollView implemented via UIViewRepresentable bridge can't perform animation with withAnimation .
To find the cause of the problem, I used a ScrollView in SwftUI as a comparison. By comparison, it is found that SwftUI ScrollView executes withAnimation normally; however, UIScrollView implemented through UIViewRepresentable bridge cannot specify animation.
May I ask if it is because of my incorrect use of UIViewRepresentable updateUIView?
I also found related articles, such as https://github.com/rcarver/swift-matched-animation It seems that the solution is mentioned, but it does not actually solve my problem.
English is not very good, I don't know if I can understand this description ðŸ˜
import SwiftUI
import UIKit
struct FriendView: View {
#State var display = false
var body: some View {
VStack {
// UIViewRepresentable + UIKit
UScrollView {
VStack {
RoundedRectangle(cornerRadius: 10)
.fill(self.display ? .red.opacity(0.3) : .blue.opacity(0.3))
.frame(width: 200, height: self.display ? 200 : 100)
.onTapGesture {
withAnimation {
self.display.toggle()
}
}
}
}
// SwiftUI
ScrollView {
VStack {
RoundedRectangle(cornerRadius: 10)
.fill(self.display ? .red.opacity(0.3) : .blue.opacity(0.3))
.frame(width: 200, height: self.display ? 200 : 100)
.onTapGesture {
withAnimation {
self.display.toggle()
}
}
}
}
}
}
}
The following is the specific implementation of UIScrollView in UIKit
struct UScrollView<Content: View>: UIViewRepresentable {
typealias UIViewType = UIScrollView
var content: () -> Content
let scrollView: UIScrollView = {
let view = UIScrollView()
return view
}()
var host: UIHostingController<AnyView> = UIHostingController(
rootView: AnyView(EmptyView())
)
init(#ViewBuilder content: #escaping () -> Content) {
self.content = content
}
func makeUIView(context: Context) -> UIScrollView {
host.rootView = AnyView(self.content())
host.view.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(host.view)
scrollView.addConstraints([
host.view.topAnchor.constraint(equalTo: scrollView.topAnchor),
host.view.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
host.view.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
host.view.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
host.view.widthAnchor.constraint(equalTo: scrollView.widthAnchor)
])
return scrollView
}
func updateUIView(_ uiView: UIScrollView, context: Context) {
host.rootView = AnyView(self.content())
host.view.translatesAutoresizingMaskIntoConstraints = false
uiView.addSubview(host.view)
uiView.addConstraints([
host.view.topAnchor.constraint(equalTo: uiView.topAnchor),
host.view.leadingAnchor.constraint(equalTo: uiView.leadingAnchor),
host.view.trailingAnchor.constraint(equalTo: uiView.trailingAnchor),
host.view.bottomAnchor.constraint(equalTo: uiView.bottomAnchor),
host.view.widthAnchor.constraint(equalTo: uiView.widthAnchor)
])
}
}
Comparing the execution effect, 1 withAnimation is invalid, 2 withAnimation is valid
I am developing an iOS app using the SwiftUI. I need to implement the "pinch to zoom" feature in the app so i tried using the SwiftUI's ScrollView but went in to the problems of not able to pinch and drag the content at the same time as discussed in the question here. So i tried using the UIKit's UIScrollView in an UIViewRepresentable as suggested in the same thread. The problem i am facing now is when i pinch zoom the view the following error is displayed in the console and view doesn't zoom.
[Assert] -[UIScrollView _clampedZoomScale:allowRubberbanding:]: Must be called with non-zero scale
My UIViewRepresentable does not occupy the entire screen and is embedded in a VStack that occupies some portion on the screen along with other elements. I am using NavigationView that holds the VStack. I have an ObservableObject as a state on the main view. I update few #Published properties on this ObservableObject from .onAppear() of the main view. When i stop updating these properties, the zoom seems to be working as expected. I am not sure what is causing the issue, can some one please help if you have faced the above error? Thanks in advance.
I could replicate this with a sample code provided below.
TestScrollViewApp.swift
#main
struct TestScrollViewApp: App {
var body: some Scene {
WindowGroup {
TestView(interactor: TestInteractor())
}
}
}
TestView.swift
import Foundation
import SwiftUI
struct TestView: View {
#ObservedObject var interactor : TestInteractor
var body: some View {
ZStack{
NavigationView{
VStack{
Text("Hi there!")
HStack{
Text("HI i am beside map")
NativeScrollView()
}
Text("Hi I am footer!")
}
}.navigationViewStyle(StackNavigationViewStyle())
}.onAppear{
interactor.setUp()
}
}
}
struct NativeScrollView: UIViewRepresentable {
let imageview = UIImageView()
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, UIScrollViewDelegate {
let parent: NativeScrollView
var zoomableView: UIView?
init(_ parent: NativeScrollView) {
self.parent = parent
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return zoomableView
}
}
func makeUIView(context: Context) -> UIScrollView {
let scrollView = UIScrollView()
scrollView.delegate = context.coordinator
scrollView.isScrollEnabled = true
scrollView.bouncesZoom = true;
imageview.contentMode = .scaleAspectFit
imageview.autoresizingMask = [.flexibleWidth,.flexibleHeight]
//add the image view
imageview.image = UIImage(named: "mapscreen")
scrollView.addSubview(imageview)
scrollView.minimumZoomScale = 1.0
scrollView.maximumZoomScale = 4.0
return scrollView
}
func updateUIView(_ uiView: UIScrollView, context: Context) {
context.coordinator.zoomableView = imageview
}
}
TestInteractor.swift
class TestInteractor:ObservableObject{
#Published var hasFooter = true
func setUp(){
hasFooter = false
}
}
I am learning Swift & SwiftUI as a hobby with no UIKit background, so I am not sure if this is currently possible. I would really like to use UIKit's context menus with SwiftUI (e.g. to implement submenus, action attributes and maybe custom preview providers).
My original idea was to create a LegacyContextMenuView with UIViewControllerRepresentable. Then I'd use a UIHostingController to add a SwiftUI View as a child of a UIViewController ContainerViewController to which I'd add a UIContextMenuInteraction.
My current solution kinda works but when the context menu is activated the preview frame of the 'ContainerViewController' view does not fit the size of UIHostingController view. I am not familiar with UIKit's layout system so I'd like to know:
Is it possible to add such constrains while the preview is activated?
Is it possible to preserve the clipShape of the underlying SwiftUI view inside the preview provider?
The code:
// MARK: - Describes a UIKit Context Menu
struct LegacyContextMenu {
let title: String
let actions: [UIAction]
var actionProvider: UIContextMenuActionProvider {
{ _ in
UIMenu(title: title, children: actions)
}
}
init(actions: [UIAction], title: String = "") {
self.actions = actions
self.title = title
}
}
// MARK: - A View that brings UIKit context menus into the SwiftUI world
struct LegacyContextMenuView<Content: View>: UIViewControllerRepresentable {
let content: Content
let menu: LegacyContextMenu
func makeUIViewController(context: Context) -> UIViewController {
let controller = ContainerViewController(rootView: content)
let menuInteraction = UIContextMenuInteraction(delegate: context.coordinator)
controller.view.addInteraction(menuInteraction)
return controller
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) { }
func makeCoordinator() -> Coordinator { Coordinator(parent: self) }
class Coordinator: NSObject, UIContextMenuInteractionDelegate {
let parent: LegacyContextMenuView
init(parent: LegacyContextMenuView) { self.parent = parent }
func contextMenuInteraction(
_ interaction: UIContextMenuInteraction,
configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration?
{
// previewProvider nil = using the default UIViewController: ContainerViewController
UIContextMenuConfiguration(identifier: nil, previewProvider: nil, actionProvider: parent.menu.actionProvider)
}
}
class ContainerViewController: UIViewController {
let hostingController: UIHostingController<Content>
init(rootView: Content) {
self.hostingController = UIHostingController(rootView: rootView)
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func viewDidLoad() {
super.viewDidLoad()
setupHostingController()
setupContraints()
// Additional setup required?
}
func setupHostingController() {
addChild(hostingController)
view.addSubview(hostingController.view)
hostingController.didMove(toParent: self)
}
// Not familiar with UIKit's layout system so unsure if this is the best approach
func setupContraints() {
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
view.addConstraints([
hostingController.view.topAnchor.constraint(equalTo: view.topAnchor),
hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
hostingController.view.leftAnchor.constraint(equalTo: view.leftAnchor),
hostingController.view.rightAnchor.constraint(equalTo: view.rightAnchor)
])
}
}
}
// MARK: - Simulate SwiftUI syntax
extension View {
func contextMenu(_ legacyContextMenu: LegacyContextMenu) -> some View {
self.modifier(LegacyContextViewModifier(menu: legacyContextMenu))
}
}
struct LegacyContextViewModifier: ViewModifier {
let menu: LegacyContextMenu
func body(content: Content) -> some View {
LegacyContextMenuView(content: content, menu: menu)
}
}
Then to test, I use this:
// MARK - A sample view with custom content shape and a dynamic frame
struct SampleView: View {
#State private var isLarge = false
let viewClipShape = RoundedRectangle(cornerRadius: 50.0)
var body: some View {
ZStack {
Color.blue
Text(isLarge ? "Large" : "Small")
.foregroundColor(.white)
.font(.largeTitle)
}
.onTapGesture { isLarge.toggle() }
.clipShape(viewClipShape)
.contentShape(viewClipShape)
.frame(height: isLarge ? 250 : 150)
.animation(.easeInOut, value: isLarge)
}
}
struct ContentView: View {
var body: some View {
SampleView()
.contextMenu(LegacyContextMenu(actions: [sampleAction], title: "My Menu"))
.padding(.horizontal)
}
let sampleAction = UIAction(
title: "Remove",
image: UIImage(systemName: "trash.fill"),
identifier: nil,
attributes: UIMenuElement.Attributes.destructive,
handler: { _ in print("Pressed 'Remove'") })
}
While long pressing, the context menu scaling animation respects the content shape of SampleView for both small and large sizes, but the preview pops out like this:
you must set preferredContentSize of ViewController to fit content size u want
I found nowhere an example how to integrate it with swiftui. Does anybody found a tutorial?
The problem is the part with the root controller.
in the Apple SwiftUI tutorial - integration in SwiftUI
you can find that how to solve this question with UIViewControllerRepresentable
and I create an example like this
import GoogleMobileAds
import SwiftUI
import UIKit
struct GADBannerViewController: UIViewControllerRepresentable {
func makeUIViewController(context: Context) -> UIViewController {
let view = GADBannerView(adSize: kGADAdSizeBanner)
let viewController = UIViewController()
view.adUnitID = "your ad unit id in there."
view.rootViewController = viewController
viewController.view.addSubview(view)
viewController.view.frame = CGRect(origin: .zero, size: kGADAdSizeBanner.size)
view.load(GADRequest())
return viewController
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {}
}
then you can using GADBannerViewController in your SwiftUI view's body like that
HStack {
Spacer()
GADBannerViewController()
.frame(width: kGADAdSizeBanner.size.width, height: kGADAdSizeBanner.size.height)
Spacer()
}
if you have any questions, please let me know.👌
To improve on Mcatach and avoid adding the view to the app's root view controller:
struct GADBannerViewController: UIViewControllerRepresentable {
#State private var banner: GADBannerView = GADBannerView(adSize: kGADAdSizeBanner)
func makeUIViewController(context: Context) -> UIViewController {
let bannerSize = GADBannerViewController.getAdBannerSize()
let viewController = UIViewController()
banner.adSize = bannerSize
banner.adUnitID = "ca-pub-ad-id-12345678"
banner.rootViewController = viewController
viewController.view.addSubview(banner)
viewController.view.frame = CGRect(origin: .zero, size: bannerSize.size)
banner.load(Ads.createRequest())
return viewController
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context){
let bannerSize = GADBannerViewController.getAdBannerSize()
banner.frame = CGRect(origin: .zero, size: bannerSize.size)
banner.load(Ads.createRequest())
}
static func getAdBannerSize() -> GADAdSize {
if let rootView = UIApplication.shared.windows.first?.rootViewController?.view {
let frame = rootView.frame.inset(by: rootView.safeAreaInsets)
return GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(frame.width)
}
//No root VC, use 320x50 ad banner
return kGADAdSizeBanner
}
}
The layout code:
private func adSection() -> some View {
HStack {
let size = GADBannerViewController.getAdBannerSize()
Spacer()
GADBannerViewController()
.frame(width: size.size.width, height: size.size.height)
Spacer()
}
}
You should use UIViewRepresentable instead of UIViewControllerRepresentable.
I implemented the Adaptive banner with this code:
struct AdView : UIViewRepresentable {
#State private var banner: GADBannerView = GADBannerView(adSize: kGADAdSizeBanner)
func makeUIView(context: UIViewRepresentableContext<AdView>) -> GADBannerView {
#if DEBUG
banner.adUnitID = "ca-app-pub-debug"
#else
banner.adUnitID = "ca-app-pub-prod"
#endif
guard let rootViewController = UIApplication.shared.windows.first?.rootViewController else {
return banner
}
banner.rootViewController = rootViewController
let frame = { () -> CGRect in
return banner.rootViewController!.view.frame.inset(by: banner.rootViewController!.view.safeAreaInsets)
}()
let viewWidth = frame.size.width
banner.adSize = GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth)
banner.load(GADRequest())
return banner
}
func updateUIView(_ uiView: GADBannerView, context: UIViewRepresentableContext<AdView>) {
}
}
Then you can call on your Stack using
AdView().frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 300)
.frame(width: kGADAdSizeBanner.size.width, height: kGADAdSizeBanner.size.height)