如何处理UIViewControllerRepresentable包装器中的NavigationLink?

时间:2019-08-14 12:39:14

标签: ios swift swiftui navigationlink

因此,我尝试创建自定义分页scrollView。我已经能够创建该包装器,并且该包装器中的内容包含一个自定义View。在该自定义视图中,按下时我有两个NavigationLink按钮应将用户带到两个不同的视图。

那些NavigationLink按钮不起作用。

scrollViewWrapper在NavigationView内部。我创建了一个测试按钮,它只是一个简单的按钮,似乎可以正常工作。因此,使用NavigationLink和自定义UIViewControllerRepresentable可能会导致我无法正确执行某些操作。

这是我使用自定义包装的地方。

NavigationView {
            UIScrollViewWrapper {
                HStack(spacing: 0) {
                    ForEach(self.onboardingDataArray, id: \.id) { item in
                          OnboardingView(onboardingData: item)
                                .frame(width: geometry.size.width, height: geometry.size.height)
                       }
                    }
            }.frame(width: geometry.size.width, height: geometry.size.height)
             .background(Color.blue)
           }

入职视图:

struct OnboardingView: View {
var onboardingData: OnboardingModel

var body: some View {
    GeometryReader { geometry in
        VStack(spacing: 10) {
            Spacer()
            Image("\(self.onboardingData.image)")
                .resizable()
                .frame(width: 300, height: 300)
                .aspectRatio(contentMode: ContentMode.fit)
                .clipShape(Circle())
                .padding(20)

            Text("\(self.onboardingData.titleText)")
                .frame(width: geometry.size.width, height: 20, alignment: .center)
                .font(.title)

            Text("\(self.onboardingData.descriptionText)")
                .lineLimit(nil)
                .padding(.leading, 15)
                .padding(.trailing, 15)
                .font(.system(size: 16))
                .frame(width: geometry.size.width, height: 50, alignment: .center)
                .multilineTextAlignment(.center)
            Spacer(minLength: 20)
            if self.onboardingData.showButton ?? false {
                VStack {
                    Button(action: {
                        print("Test")
                    }) {
                        Text("Test Button")
                    }
                    NavigationLink(destination: LogInView()) {
                        Text("Login!")
                    }
                    NavigationLink(destination: SignUpView()) {
                        Text("Sign Up!")
                    }
                }
            }

            Spacer()
        }
    }
}
    }

自定义ScrollView包装器代码:

struct UIScrollViewWrapper<Content: View>: UIViewControllerRepresentable {
var content: () -> Content

init(@ViewBuilder content: @escaping () -> Content) {
    self.content = content
}

func makeUIViewController(context: Context) -> UIScrollViewController {
    let vc = UIScrollViewController()
    vc.hostingController.rootView = AnyView(self.content())
    return vc
}

func updateUIViewController(_ viewController: UIScrollViewController, context: Context) {
    viewController.hostingController.rootView = AnyView(self.content())
  }
}

class UIScrollViewController: UIViewController {

lazy var scrollView: UIScrollView = {
    let view = UIScrollView()
    view.isPagingEnabled = true
    return view
}()

var hostingController: UIHostingController<AnyView> = UIHostingController(rootView: AnyView(EmptyView()))

override func viewDidLoad() {
    super.viewDidLoad()

    self.view.addSubview(self.scrollView)
    self.pinEdges(of: self.scrollView, to: self.view)

    self.hostingController.willMove(toParent: self)
    self.scrollView.addSubview(self.hostingController.view)
    self.pinEdges(of: self.hostingController.view, to: self.scrollView)
    self.hostingController.didMove(toParent: self)
}

func pinEdges(of viewA: UIView, to viewB: UIView) {
      viewA.translatesAutoresizingMaskIntoConstraints = false
      viewB.addConstraints([
          viewA.leadingAnchor.constraint(equalTo: viewB.leadingAnchor),
          viewA.trailingAnchor.constraint(equalTo: viewB.trailingAnchor),
          viewA.topAnchor.constraint(equalTo: viewB.topAnchor),
          viewA.bottomAnchor.constraint(equalTo: viewB.bottomAnchor),
      ])
  }

4 个答案:

答案 0 :(得分:0)

发生这种情况是因为您使用的是UIViewControllerRepresentable而不是UIViewRepresentable。我猜想UIScrollViewController会阻止目标控制器被当前控制器呈现。

请尝试使用上面的代码:

import UIKit
import SwiftUI

struct ScrollViewWrapper<Content>: UIViewRepresentable where Content: View{
    func updateUIView(_ uiView: UIKitScrollView, context: UIViewRepresentableContext<ScrollViewWrapper<Content>>) {

    }


    typealias UIViewType = UIKitScrollView

    let content: () -> Content
    var showsIndicators : Bool

    public init(_ axes: Axis.Set = .vertical, showsIndicators: Bool = true, @ViewBuilder content: @escaping () -> Content) {
        self.content = content
        self.showsIndicators = showsIndicators

    }

    func makeUIView(context: UIViewRepresentableContext<ScrollViewWrapper>) -> UIViewType {
        let hosting = UIHostingController(rootView: AnyView(content()))
        let width = UIScreen.main.bounds.width
        let size = hosting.view.sizeThatFits(CGSize(width: width, height: CGFloat.greatestFiniteMagnitude))
        hosting.view.frame = CGRect(x: 0, y: 0, width: width, height: size.height)
        let view = UIKitScrollView()
        view.delegate = view
        view.alwaysBounceVertical = true
        view.addSubview(hosting.view)
        view.contentSize = CGSize(width: width, height: size.height)
        return view
    }

}


class UIKitScrollView: UIScrollView, UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        print(scrollView.contentOffset) // Do whatever you want.
    }
}

答案 1 :(得分:0)

这是对上述解决方案的扩展,它从不滚动内部内容。

我遇到了类似的问题。我发现问题出在 UIViewControllerRepresentable 。可以使用 UIViewRepresentable ,尽管我不确定问题是什么。我可以使用下面的代码来完成Navigationlink的工作。

struct SwiftyUIScrollView<Content>: UIViewRepresentable where Content: View {
typealias UIViewType = Scroll

var content: () -> Content
var pagingEnabled: Bool = false
var hideScrollIndicators: Bool = false
@Binding var shouldUpdate: Bool
@Binding var currentIndex: Int

var onScrollIndexChanged: ((_ index: Int) -> Void)

public init(pagingEnabled: Bool,
            hideScrollIndicators: Bool,
            currentIndex: Binding<Int>,
            shouldUpdate: Binding<Bool>,
            @ViewBuilder content: @escaping () -> Content, onScrollIndexChanged: @escaping ((_ index: Int) -> Void)) {
    self.content = content
    self.pagingEnabled = pagingEnabled
    self._currentIndex = currentIndex
    self._shouldUpdate = shouldUpdate
    self.hideScrollIndicators = hideScrollIndicators
    self.onScrollIndexChanged = onScrollIndexChanged
}

func makeUIView(context: UIViewRepresentableContext<SwiftyUIScrollView>) -> UIViewType {
    let hosting = UIHostingController(rootView: content())
    let view = Scroll(hideScrollIndicators: hideScrollIndicators, isPagingEnabled: pagingEnabled)
    view.scrollDelegate = context.coordinator
    view.alwaysBounceHorizontal = true
    view.addSubview(hosting.view)
    makefullScreen(of: hosting.view, to: view)
    return view
}

class Coordinator: NSObject, ScrollViewDelegate {
    func didScrollToIndex(_ index: Int) {
        self.parent.onScrollIndexChanged(index)
    }

    var parent: SwiftyUIScrollView

    init(_ parent: SwiftyUIScrollView) {
        self.parent = parent
    }
}

func makeCoordinator() -> SwiftyUIScrollView<Content>.Coordinator {
    Coordinator(self)
}

func updateUIView(_ uiView: Scroll, context: UIViewRepresentableContext<SwiftyUIScrollView<Content>>) {
    if shouldUpdate {
        uiView.scrollToIndex(index: currentIndex)
    }
}

func makefullScreen(of childView: UIView, to parentView: UIView) {
    childView.translatesAutoresizingMaskIntoConstraints = false
    childView.leftAnchor.constraint(equalTo: parentView.leftAnchor).isActive = true
    childView.rightAnchor.constraint(equalTo: parentView.rightAnchor).isActive = true
    childView.topAnchor.constraint(equalTo: parentView.topAnchor).isActive = true
    childView.bottomAnchor.constraint(equalTo: parentView.bottomAnchor).isActive = true
}
}

然后创建一个新类来处理滚动视图的委托。您还可以将以下代码包含在 UIViewRepresentable 中。但是我更喜欢将其分开以得到干净的代码。

class Scroll: UIScrollView, UIScrollViewDelegate {

var hideScrollIndicators: Bool = false
var scrollDelegate: ScrollViewDelegate?
var tileWidth = 270
var tileMargin = 20

init(hideScrollIndicators: Bool, isPagingEnabled: Bool) {
    super.init(frame: CGRect.zero)
    showsVerticalScrollIndicator = !hideScrollIndicators
    showsHorizontalScrollIndicator = !hideScrollIndicators
    delegate = self
    self.isPagingEnabled = isPagingEnabled
}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    let currentIndex = scrollView.contentOffset.x / CGFloat(tileWidth+tileMargin)
    scrollDelegate?.didScrollToIndex(Int(currentIndex))
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let currentIndex = scrollView.contentOffset.x / CGFloat(tileWidth+tileMargin)
    scrollDelegate?.didScrollToIndex(Int(currentIndex))
}

func scrollToIndex(index: Int) {
    let newOffSet = CGFloat(tileWidth+tileMargin) * CGFloat(index)
    contentOffset = CGPoint(x: newOffSet, y: contentOffset.y)
}
}

现在要实现scrollView,请使用以下代码。

@State private var activePageIndex: Int = 0
@State private var shouldUpdateScroll: Bool = false

SwiftyUIScrollView(pagingEnabled: false, hideScrollIndicators: true, currentIndex: $activePageIndex, shouldUpdate: $shouldUpdateScroll, content: {
            HStack(spacing: 20) {
                ForEach(self.data, id: \.id) { data in
                    NavigationLink(destination: self.getTheNextView(data: data)) {
                        self.cardView(data: data)
                    }
                }
            }
            .padding(.horizontal, 30.0)
        }, onScrollIndexChanged: { (newIndex) in
           shouldUpdateScroll = false
           activePageIndex = index
            // Your own required handling
        })


func getTheNextView(data: Any) -> AnyView {
    // Return the required destination View
}

答案 2 :(得分:0)

正如其他答案所述,将NavigationLink放入UIViewControllerRepresentable中存在问题。

我通过将我的UIViewControllerRepresentable和一个NavigationLink包裹在一个View内并从UIViewControllerRepresentable内部以编程方式激活NavigationLink来解决此问题。

例如:

struct MyView: View
{        
    @State var destination: AnyView? = nil
    @State var is_active: Bool = false

    var body: some View
    {
        ZStack
        {
            MyViewControllerRepresentable( self )

            NavigationLink( destination: self.destination, isActive: self.$is_active )
            {
                EmptyView()
            }
        }
    }

    func goTo( destination: AnyView )
   {
        self.destination = destination
        self.is_active = true
   }
}

在我的情况下,我将MyView实例传递给MyViewControllerRepresentable包装的UIViewController,并在单击按钮时调用了goTo(destination:AnyView)方法。

我们的案例之间的区别在于,我的UIViewController是我自己的用UIKit编写的类(与UIHostingController相比)。如果您使用的是UIHostingController,则可以使用包含destinationis_active变量的共享ObservableObject。您需要将2个NavigationLinks更改为Button,这些按钮的操作方法会更改ObservableObject的destinationis_active变量。

答案 3 :(得分:-1)

您是否设置了触发的Segues?如果您使用的是Xcode,则可以右键单击在主故事板上创建的按钮。如果未设置,则可以转到右上侧栏上的连接检查器,在其中可以找到文件检查器,身份检查器,属性检查器...,并指定希望按钮执行的操作。