I am using this implementation for showing UISheetPresentationController in SwiftUI
import SwiftUI
#available(iOS 15.0, macCatalyst 15.0,*)
extension View {
func adaptiveSheet<T: View>(isPresented: Binding<Bool>, detents : [UISheetPresentationController.Detent] = [.medium(), .large()], largestUndimmedDetentIdentifier: UISheetPresentationController.Detent.Identifier? = .medium, prefersScrollingExpandsWhenScrolledToEdge: Bool = false, prefersEdgeAttachedInCompactHeight: Bool = true, prefersGrabberVisible: Bool = false, disableSwipeToDismiss: Bool = false, preferredCornerRadius: CGFloat? = nil, #ViewBuilder content: #escaping () -> T)-> some View {
print("\(#function) :: isPresented == \(isPresented)")
return modifier(AdaptiveSheet<T>(isPresented: isPresented, detents : detents, largestUndimmedDetentIdentifier: largestUndimmedDetentIdentifier, prefersScrollingExpandsWhenScrolledToEdge: prefersScrollingExpandsWhenScrolledToEdge, prefersEdgeAttachedInCompactHeight: prefersEdgeAttachedInCompactHeight, prefersGrabberVisible: prefersGrabberVisible, disableSwipeToDismiss: disableSwipeToDismiss, preferredCornerRadius: preferredCornerRadius, sheetContent: content))
}
}
#available(iOS 15.0, macCatalyst 15.0,*)
struct AdaptiveSheet<T: View>: ViewModifier {
#Binding var isPresented: Bool
let detents : [UISheetPresentationController.Detent]
let largestUndimmedDetentIdentifier: UISheetPresentationController.Detent.Identifier?
let prefersScrollingExpandsWhenScrolledToEdge: Bool
let prefersEdgeAttachedInCompactHeight: Bool
let prefersGrabberVisible: Bool
let disableSwipeToDismiss: Bool
let preferredCornerRadius: CGFloat?
#ViewBuilder let sheetContent: T
func body(content: Content) -> some View {
print("AdaptiveSheet :: \(#function) :: isPresented == \(isPresented)")
return content.overlay(
CustomSheet_UI(isPresented: $isPresented, detents: detents, largestUndimmedDetentIdentifier: largestUndimmedDetentIdentifier, prefersScrollingExpandsWhenScrolledToEdge: prefersScrollingExpandsWhenScrolledToEdge, prefersEdgeAttachedInCompactHeight: prefersEdgeAttachedInCompactHeight, prefersGrabberVisible: prefersGrabberVisible, disableSwipeToDismiss: disableSwipeToDismiss,preferredCornerRadius: preferredCornerRadius, content: {sheetContent}).frame(width: 0, height: 0)
)
.onChange(of: isPresented, perform: { value in
print("AdaptiveSheet :: onChange :: isPresented == \(value)")
})
//}
}
}
#available(iOS 15.0, macCatalyst 15.0,*)
struct CustomSheet_UI<T: View>: UIViewControllerRepresentable {
#Binding var isPresented: Bool
var detents : [UISheetPresentationController.Detent] = [.medium(), .large()]
var largestUndimmedDetentIdentifier: UISheetPresentationController.Detent.Identifier? = .medium
var prefersScrollingExpandsWhenScrolledToEdge: Bool = false
var prefersEdgeAttachedInCompactHeight: Bool = true
var prefersGrabberVisible: Bool = false
var disableSwipeToDismiss: Bool = false
var preferredCornerRadius: CGFloat?
#ViewBuilder let content: T
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIViewController(context: Context) -> CustomSheetViewController<T> {
print("CustomSheet_UI :: \(#function) :: isPresented == \(isPresented)")
let vc = CustomSheetViewController(coordinator: context.coordinator, detents : detents, largestUndimmedDetentIdentifier: largestUndimmedDetentIdentifier, prefersScrollingExpandsWhenScrolledToEdge: prefersScrollingExpandsWhenScrolledToEdge, prefersEdgeAttachedInCompactHeight: prefersEdgeAttachedInCompactHeight, prefersGrabberVisible: prefersGrabberVisible, disableSwipeToDismiss: disableSwipeToDismiss, preferredCornerRadius: preferredCornerRadius, content: {content})
return vc
}
func updateUIViewController(_ uiViewController: CustomSheetViewController<T>, context: Context) {
print("CustomSheet_UI :: \(#function) :: isPresented == \(isPresented)")
print("CustomSheet_UI :: \(#function) :: context.coordinator.parent.isPresented == \(context.coordinator.parent.isPresented)")
if isPresented {
uiViewController.presentModalView()
}else{
uiViewController.dismissModalView()
}
}
class Coordinator: NSObject, UIAdaptivePresentationControllerDelegate {
var parent: CustomSheet_UI
var isPresented: Bool = false
init(_ parent: CustomSheet_UI) {
print("CustomSheet_UI :: \(#function) :: parent.isPresented == \(parent.isPresented)")
self.parent = parent
}
//Adjust the variable when the user dismisses with a swipe
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
print("CustomSheet_UI.Coordinator :: \(#function) :: parent.isPresented == \(parent.isPresented)")
if parent.isPresented{
parent.isPresented = false
}
}
}
}
#available(iOS 15.0, macCatalyst 15.0,*)
class CustomSheetViewController<Content: View>: UIViewController {
let content: Content
var coordinator: CustomSheet_UI<Content>.Coordinator
let detents : [UISheetPresentationController.Detent]
let largestUndimmedDetentIdentifier: UISheetPresentationController.Detent.Identifier?
let prefersScrollingExpandsWhenScrolledToEdge: Bool
let prefersEdgeAttachedInCompactHeight: Bool
let prefersGrabberVisible: Bool
let disableSwipeToDismiss: Bool
let preferredCornerRadius: CGFloat?
private var isLandscape: Bool = UIDevice.current.orientation.isLandscape
init(coordinator: CustomSheet_UI<Content>.Coordinator, detents : [UISheetPresentationController.Detent] = [.medium(), .large()], largestUndimmedDetentIdentifier: UISheetPresentationController.Detent.Identifier? = .medium, prefersScrollingExpandsWhenScrolledToEdge: Bool = false, prefersEdgeAttachedInCompactHeight: Bool = true, prefersGrabberVisible: Bool, disableSwipeToDismiss: Bool, preferredCornerRadius: CGFloat?, #ViewBuilder content: #escaping () -> Content) {
print("CustomSheetViewController :: \(#function) :: isPresented == \(coordinator.parent.isPresented)")
self.content = content()
self.coordinator = coordinator
self.detents = detents
self.largestUndimmedDetentIdentifier = largestUndimmedDetentIdentifier
self.prefersEdgeAttachedInCompactHeight = prefersEdgeAttachedInCompactHeight
self.prefersScrollingExpandsWhenScrolledToEdge = prefersScrollingExpandsWhenScrolledToEdge
self.prefersGrabberVisible = prefersGrabberVisible
self.disableSwipeToDismiss = disableSwipeToDismiss
self.preferredCornerRadius = preferredCornerRadius
super.init(nibName: nil, bundle: .main)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func dismissModalView(){
print("CustomSheetViewController :: \(#function) :: isPresented == \(coordinator.parent.isPresented)")
dismiss(animated: true, completion: nil)
}
func presentModalView(){
print("CustomSheetViewController :: \(#function) :: isPresented == \(coordinator.parent.isPresented)")
let hostingController = UIHostingController(rootView: content)
//allows background color to be decided by SwiftUI content.
// Incase you want to use a Material that gives transparency
hostingController.view.backgroundColor = nil
hostingController.modalPresentationStyle = .popover
hostingController.presentationController?.delegate = coordinator as UIAdaptivePresentationControllerDelegate
hostingController.modalTransitionStyle = .coverVertical
hostingController.isModalInPresentation = disableSwipeToDismiss
if let hostPopover = hostingController.popoverPresentationController {
hostPopover.sourceView = super.view
let sheet = hostPopover.adaptiveSheetPresentationController
//As of 13 Beta 4 if .medium() is the only detent in landscape error occurs
sheet.detents = (isLandscape ? [.large()] : detents)
sheet.largestUndimmedDetentIdentifier =
largestUndimmedDetentIdentifier
sheet.prefersScrollingExpandsWhenScrolledToEdge =
prefersScrollingExpandsWhenScrolledToEdge
sheet.prefersEdgeAttachedInCompactHeight =
prefersEdgeAttachedInCompactHeight
sheet.widthFollowsPreferredContentSizeWhenEdgeAttached = true
sheet.prefersGrabberVisible = prefersGrabberVisible
sheet.preferredCornerRadius = preferredCornerRadius
}
if presentedViewController == nil{
present(hostingController, animated: true, completion: nil)
}
}
/// To compensate for l orientation
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
if UIDevice.current.orientation.isLandscape {
isLandscape = true
self.presentedViewController?.popoverPresentationController?.adaptiveSheetPresentationController.detents = [.large()]
} else {
isLandscape = false
self.presentedViewController?.popoverPresentationController?.adaptiveSheetPresentationController.detents = detents
}
super.viewWillTransition(to: size, with: coordinator)
}
}
when I change iOn value, it doesn't change the content. Please consider the following demo view
import SwiftUI
struct TestView: View {
#State var isOn = false
var body: some View {
VStack {
Toggle("Is on?", isOn: $isOn)
Spacer()
}
.padding()
.adaptiveSheet(isPresented: self.$isOn) {
let _ = print("sheet => rendered with value:", isOn)
if isOn {
let _ = print("sheet => inside isOn = true condition:", isOn)
Rectangle()
.fill(Color.green)
} else {
let _ = print("sheet => inside isOn = false condition:", isOn)
Rectangle()
.fill(Color.red)
}
}
}
}
struct TestView_Previews: PreviewProvider {
static var previews: some View {
TestView()
}
}
changing isOn value triggers the following line
let _ = print("sheet => inside isOn = false condition:", isOn)
but for some reason the UI doesn't get updated. The red color persists no matter what I do.
Related
I have a multi line text field, and need it to become a first responder when it appears. Also, it needs to resign as a first responder when the onCommit parameter of MultiLineTextField is fired, or one of 2 buttons are tapped.
As it stands, the keyboard dismisses when it should but immediately reappears when it shouldn't.
I know I could just use the new iOS 16 TextField .axis parameter, but I need to stick with iOS 15.5, hence the long drawn out code below.
import SwiftUI
struct MultilineTextField: View {
private var placeholder: String
private var onCommit: (() -> Void)?
#State private var viewHeight: CGFloat = 40 //start with one line
#State private var shouldShowPlaceholder = false
#Binding private var text: String
private var internalText: Binding<String> {
Binding<String>(get: { self.text } ) {
self.text = $0
self.shouldShowPlaceholder = $0.isEmpty
}
}
var body: some View {
UITextViewWrapper(text: self.internalText, calculatedHeight: $viewHeight, onDone: onCommit)
.frame(minHeight: viewHeight, maxHeight: viewHeight)
.background(placeholderView, alignment: .topLeading)
}
var placeholderView: some View {
Group {
if shouldShowPlaceholder {
Text(placeholder).foregroundColor(.gray)
.padding(.leading, 4)
.padding(.top, 8)
}
}
}
init (_ placeholder: String = "", text: Binding<String>, onCommit: (() -> Void)? = nil) {
self.placeholder = placeholder
self.onCommit = onCommit
self._text = text
self._shouldShowPlaceholder = State<Bool>(initialValue: self.text.isEmpty)
}
}
private struct UITextViewWrapper: UIViewRepresentable {
typealias UIViewType = UITextView
#Binding var text: String
#Binding var calculatedHeight: CGFloat
var onDone: (() -> Void)?
func makeUIView(context: UIViewRepresentableContext<UITextViewWrapper>) -> UITextView {
let textField = UITextView()
textField.delegate = context.coordinator
textField.isEditable = true
textField.font = UIFont.preferredFont(forTextStyle: .body)
textField.isSelectable = true
textField.isUserInteractionEnabled = true
textField.autocorrectionType = .no
textField.isScrollEnabled = false
textField.backgroundColor = UIColor.clear
textField.keyboardType = .asciiCapable
textField.textColor = .systemBlue
textField.textAlignment = .center
if nil != onDone {
textField.returnKeyType = .done
}
textField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
return textField
}
func updateUIView(_ uiView: UITextView, context: UIViewRepresentableContext<UITextViewWrapper>) {
if uiView.text != self.text {
uiView.text = self.text
}
if uiView.window != nil, !uiView.isFirstResponder {
uiView.becomeFirstResponder()
}
UITextViewWrapper.recalculateHeight(view: uiView, result: $calculatedHeight)
}
private static func recalculateHeight(view: UIView, result: Binding<CGFloat>) {
let newSize = view.sizeThatFits(CGSize(width: view.frame.size.width, height: CGFloat.greatestFiniteMagnitude))
if result.wrappedValue != newSize.height {
DispatchQueue.main.async {
result.wrappedValue = newSize.height // call in next render cycle.
}
}
}
func makeCoordinator() -> Coordinator {
return Coordinator(text: $text, height: $calculatedHeight, onDone: onDone)
}
final class Coordinator: NSObject, UITextViewDelegate {
var text: Binding<String>
var calculatedHeight: Binding<CGFloat>
var onDone: (() -> Void)?
init(text: Binding<String>, height: Binding<CGFloat>, onDone: (() -> Void)? = nil) {
self.text = text
self.calculatedHeight = height
self.onDone = onDone
}
func textViewDidChange(_ uiView: UITextView) {
text.wrappedValue = uiView.text
UITextViewWrapper.recalculateHeight(view: uiView, result: calculatedHeight)
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if let onDone = self.onDone, text == "\n" {
textView.resignFirstResponder()
onDone()
return false
}
return true
}
}
}
MultilineTextField Usage:
MultilineTextField("", text: Binding<String>(
get: { userAnswer },
set: {
self.userAnswer = $0.allowedCharacters(string: $0)
self.enableHint()
}), onCommit: {
if self.userAnswer.isEmpty {
nativeForeignPlaceholder = NSMutableAttributedString(string: "Tap here to answer...")
} else {
answerDisabled = true
checkAnswer()
}
})
.overlay(RoundedRectangle(cornerRadius: 5).stroke(Color.systemBlue, lineWidth: overlayLineWidth))
.modifier(TextFieldClearButton(text: $userAnswer))
.placeholder(when: userAnswer.isEmpty) {
TextWithAttributedString(attributedString: nativeForeignPlaceholder ?? NSMutableAttributedString())
}
.font(.system(size: fontSize, weight: .regular, design: .rounded))
.lineLimit(2)
.disabled(answerDisabled)
.onAppear {
// key part: delay setting isFocused until after some-internal-iOS setup
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
answerIsFocused = true
}
}
.onTapGesture(perform: tapOnAnswerField)
.frame(dynamicWidth: 675, dynamicHeight: 100, alignment: .center)
.position(x: geometry.frame(in: .local).midX, y: geometry.frame(in: .local).midY + geometry.size.height / 8.5)
func tapOnAnswerField() {
answerIsFocused = true
}
I've a problem in SwiftUI with the searchBar appear.
There's a delay on its appear when I use NavigationLink. I saw that the problem appears only with NavigationLinks, if I use a conditional overlay or others "handmade" way to move between Views the problem doesn't appear. You know what I could do to fix the problem?
Here's my views code:
import SwiftUI
struct ContentView: View {
#State var searchText = ""
var body: some View {
NavigationView{
NavigationLink(destination: ContentView2()){
Text("Go to Sub View")
}
.navigationBarTitle("Main View")
.add(SearchBar(text: self.$searchText, hide: true, placeholder: "Search", cancelButton: true, autocapitalization: .sentences))
}
}
}
struct ContentView2 : View {
#State var searchText = ""
var body: some View {
Text("Hello, world!")
.navigationBarTitle("Sub View")
.add(SearchBar(text: self.$searchText, hide: true, placeholder: "Search", cancelButton: true, autocapitalization: .sentences))
}
}
My SearchBar code
import SwiftUI
class SearchBar: NSObject, ObservableObject {
let searchController: UISearchController = UISearchController(searchResultsController: nil)
#Binding var text: String
let hide : Bool
let placeholder : String
let cancelButton : Bool
let autocapitalization : UITextAutocapitalizationType
init(text: Binding<String>, hide: Bool, placeholder: String, cancelButton: Bool, autocapitalization: UITextAutocapitalizationType) {
self._text = text
self.hide = hide
self.placeholder = placeholder
self.cancelButton = cancelButton
self.autocapitalization = autocapitalization
super.init()
self.searchController.obscuresBackgroundDuringPresentation = false
self.searchController.searchResultsUpdater = self
self.searchController.hidesNavigationBarDuringPresentation = hide
self.searchController.automaticallyShowsCancelButton = cancelButton
self.searchController.searchBar.placeholder = placeholder
self.searchController.searchBar.autocapitalizationType = autocapitalization
}
}
extension SearchBar: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
// Publish search bar text changes.
if let searchBarText = searchController.searchBar.text {
self.text = searchBarText
}
}
}
struct SearchBarModifier: ViewModifier {
let searchBar: SearchBar
func body(content: Content) -> some View {
content
.overlay(
ViewControllerResolver { viewController in
viewController.navigationItem.searchController = self.searchBar.searchController
}
.frame(width: 0, height: 0)
)
}
}
extension View {
func add(_ searchBar: SearchBar) -> some View {
return self.modifier(SearchBarModifier(searchBar: searchBar))
}
}
My ViewController code
import SwiftUI
final class ViewControllerResolver: UIViewControllerRepresentable {
let onResolve: (UIViewController) -> Void
init(onResolve: #escaping (UIViewController) -> Void) {
self.onResolve = onResolve
}
func makeUIViewController(context: Context) -> ParentResolverViewController {
ParentResolverViewController(onResolve: onResolve)
}
func updateUIViewController(_ uiViewController: ParentResolverViewController, context: Context) { }
}
class ParentResolverViewController: UIViewController {
let onResolve: (UIViewController) -> Void
init(onResolve: #escaping (UIViewController) -> Void) {
self.onResolve = onResolve
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("Use init(onResolve:) to instantiate ParentResolverViewController.")
}
override func didMove(toParent parent: UIViewController?) {
super.didMove(toParent: parent)
if let parent = parent {
onResolve(parent)
}
}
override func viewDidAppear(_ animated: Bool) {
self.parent?.navigationItem.hidesSearchBarWhenScrolling = false
self.parent?.definesPresentationContext = true
self.parent?.navigationController?.navigationBar.sizeToFit()
}
override func viewDidDisappear(_ animated: Bool) {
self.parent?.navigationItem.hidesSearchBarWhenScrolling = false
self.parent?.definesPresentationContext = true
self.parent?.navigationController?.navigationBar.sizeToFit()
}
}
And here's a video of the problem
Set the hidesSearchBarWhenScrolling property before the SearchBar is displayed on the screen. This can be done in viewWillAppear or as in the example below:
struct SearchBarModifier: ViewModifier {
let searchBar: SearchBar
func body(content: Content) -> some View {
content
.overlay(
ViewControllerResolver { viewController in
viewController.navigationItem.searchController = self.searchBar.searchController
viewController.navigationItem.hidesSearchBarWhenScrolling = false
}
.frame(width: 0, height: 0)
)
}
}
I consider how to create SwitUI List that has as its row custom UIViews.
I create List:
List {
RowView()
}
RowView is UIViewRepresentable of UIRowView
struct RowView : UIViewRepresentable {
func makeUIView() -> UIRowView { ... }
}
UIRowView is custom view
UIRowView: UIView { ... }
Currently first rows are displayed but they are usually not layout properly and while scrolling this views disappear instead of being recycled
UPDATE
Example 1
struct NoteView: UIViewRepresentable {
// MARK: - Properties
let note: Note
let date = Date()
func makeUIView(context: Context) -> UINoteView {
let view = UINoteView()
view.note = note
return view
}
func updateUIView(_ uiView: UINoteView, context: Context) {
uiView.note = note
print("View bounds: \(uiView.bounds)")
}
}
var body: some View {
List {
ForEach(Array(notes.enumerated()), id: \.1) { (i, note) in
NoteView(note: note)
.background(Color.green)
.listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
}
}.background(Color.red)
}
Example 2 - Simplified
struct TestView : UIViewRepresentable {
let text : String
func makeUIView(context: Context) -> UILabel {
UILabel()
}
func updateUIView(_ uiView: UILabel, context: Context) {
uiView.text = text
}
}
var body: some View {
List {
ForEach(0..<30, id: \.self) { i in
TestView(text: "\(i)")
}
}
}
Both seems to work incorrectly, as rows dissapears
I had also issue with views not keeping padding and going outside of the screen if there was more content. Only several first rows (visible initially on screen layouts correctly) other disappears or jump somewhere.
UPDATE 2
Here is Autosizable UINoteView
class UINoteView: UIView {
// MARK: - Init
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupViews()
}
// MARK: - Properties
var note: Note? {
didSet {
textView.attributedText = note?.content?.parsedHtmlAttributedString(textStyle: .html)
noteFooterViewModel.note = note
}
}
// MARK: - Views
lazy var textView: UITextView = {
let textView = UITextView()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.backgroundColor = UIColor.yellow
textView.textContainer.lineBreakMode = .byWordWrapping
textView.textContainerInset = .zero
textView.textContainer.lineFragmentPadding = 0
textView.isScrollEnabled = false
textView.isSelectable = true
textView.isUserInteractionEnabled = true
textView.isEditable = false
textView.textContainer.maximumNumberOfLines = 0
return textView
}()
lazy var label: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "TEST ROW \(note?.id ?? "")"
return label
}()
lazy var vStack: UIStackView = {
let stack = UIStackView(arrangedSubviews: [
textView,
noteFooter
])
stack.axis = .vertical
stack.alignment = .fill
stack.distribution = .fill
stack.translatesAutoresizingMaskIntoConstraints = false
return stack
}()
var noteFooterViewModel = NoteFooterViewModel()
var noteFooter: UIView {
let footer = NoteFooter(viewModel: noteFooterViewModel)
let hosting = UIHostingController(rootView: footer)
hosting.view.translatesAutoresizingMaskIntoConstraints = false
return hosting.view
}
private func setupViews() {
self.backgroundColor = UIColor.green
self.addSubview(vStack)
NSLayoutConstraint.activate([
vStack.leadingAnchor.constraint(equalTo: self.leadingAnchor),
vStack.trailingAnchor.constraint(equalTo: self.trailingAnchor),
vStack.topAnchor.constraint(equalTo: self.topAnchor),
vStack.bottomAnchor.constraint(equalTo: self.bottomAnchor)
])
}
}
UPDATED ANSWER
try this:
struct TestView : UIViewRepresentable {
let text : String
var label : UILabel = UILabel()
func makeUIView(context: Context) -> UILabel {
return label
}
func updateUIView(_ uiView: UILabel, context: Context) {
uiView.text = text
}
}
struct ContentView : View {
var body: some View {
List (0..<30, id: \.self) { i in
TestView(text: "\(i)").id(i)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
I did like below. You can get the frame size even without UIViewRepresentable by getTextFrame(for note)
var body: some View {
List {
ForEach(Array(notes.enumerated()), id: \.1) { (i, note) in
NoteView(note: note)
// add this
.frame(width: getTextFrame(for: note).width, height: getTextFrame(for: note).height)
.background(Color.green)
.listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
}
}.background(Color.red)
}
func getTextFrame(for text: String, maxWidth: CGFloat? = nil, maxHeight: CGFloat? = nil) -> CGSize {
let attributes: [NSAttributedString.Key: Any] = [
.font: UIFont.preferredFont(forTextStyle: .body)
]
let attributedText = NSAttributedString(string: text, attributes: attributes)
let width = maxWidth != nil ? min(maxWidth!, CGFloat.greatestFiniteMagnitude) : CGFloat.greatestFiniteMagnitude
let height = maxHeight != nil ? min(maxHeight!, CGFloat.greatestFiniteMagnitude) : CGFloat.greatestFiniteMagnitude
let constraintBox = CGSize(width: width, height: height)
let rect = attributedText.boundingRect(with: constraintBox, options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil).integral
print(rect.size)
return rect.size
}
struct NoteView: UIViewRepresentable {
let note: String
func makeUIView(context: Context) -> UITextView {
let textView = UITextView()
textView.delegate = context.coordinator
textView.font = UIFont.preferredFont(forTextStyle: .body)
textView.isEditable = false
textView.isSelectable = true
textView.isUserInteractionEnabled = true
textView.isScrollEnabled = false
textView.backgroundColor = .clear
textView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
textView.textContainerInset = .zero
textView.textContainer.lineFragmentPadding = 0
textView.textContainer.lineBreakMode = .byWordWrapping
textView.text = note
return textView
}
func updateUIView(_ uiView: UITextView, context: Context) {
}
}
I have 2 problems in my code.
One is compile error [Cannot convert value of type 'Page1' to expected element type '_'] is shown at ★.
Another is that when backward button is pressed, Page2(blue) disappeared while alert sheet is showing.
(comment out "Page1(page: self.$page)," and then build source)
Expected behavior is that Page2(blue) does not disappear until alert button(Yes) is pressed.
Can anyone tell me how to solve these problems?
import SwiftUI
struct PageViewController: UIViewControllerRepresentable {
var controllers: [UIViewController]
#Binding var currentPage: Int
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIViewController(context: Context) -> UIPageViewController {
let pageViewController = UIPageViewController(
transitionStyle: .pageCurl,
navigationOrientation: .vertical)
pageViewController.dataSource = context.coordinator
pageViewController.delegate = context.coordinator
return pageViewController
}
func updateUIViewController(_ pageViewController: UIPageViewController, context: Context) {
pageViewController.setViewControllers(
[controllers[currentPage]], direction: .forward, animated: true)
}
class Coordinator: NSObject, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
var parent: PageViewController
init(_ pageViewController: PageViewController) {
self.parent = pageViewController
}
func pageViewController(
_ pageViewController: UIPageViewController,
viewControllerBefore viewController: UIViewController) -> UIViewController?
{
guard let index = parent.controllers.firstIndex(of: viewController) else {
return nil
}
if index == 0 {
return nil
}
return parent.controllers[index - 1]
}
func pageViewController(
_ pageViewController: UIPageViewController,
viewControllerAfter viewController: UIViewController) -> UIViewController?
{
guard let index = parent.controllers.firstIndex(of: viewController) else {
return nil
}
if index + 1 == parent.controllers.count {
return nil
}
return parent.controllers[index + 1]
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if completed,
let visibleViewController = pageViewController.viewControllers?.first,
let index = parent.controllers.firstIndex(of: visibleViewController)
{
parent.currentPage = index
}
}
}
}
struct PageView<Page: View>: View {
var viewControllers: [UIHostingController<Page>]
#Binding var currentPage: Int
init(_ views: [Page], currentPage: Binding<Int>) {
self._currentPage = currentPage
self.viewControllers = views.map { UIHostingController(rootView: $0) }
}
var body: some View {
PageViewController(controllers: viewControllers, currentPage: $currentPage)
}
}
struct ContentView: View {
#State var page: Int = 0
var body: some View {
VStack {
PageView([
Page1(page: self.$page), // ★ error
Page2(page: self.$page)// ★ error
], currentPage: $page)
}
}
}
struct Page1: View{
#Binding var page: Int
var body: some View {
ZStack{
Color.red
VStack{
Text("page1")
Button (
action: { self.page += 1 }
){
Image(systemName: "forward")
.accentColor(Color.yellow)
}
}
}
}
}
struct Page2: View{
#State private var showingAlert: Bool = false
#Binding var page: Int
var body: some View {
ZStack{
Color.blue
VStack{
Text("page2")
Button (
action: { self.showingAlert.toggle() }
){
Image(systemName: "backward")
.accentColor(Color.yellow)
}
}
.alert(isPresented: $showingAlert) {
Alert(
title: Text("Confirm"),
message: Text("Back?"),
primaryButton:
.default(Text("Yes"),
action:{ self.page -= 1 }
),
secondaryButton:
.cancel(Text("No"))
)//alert
}//alert
}
}
}
I was able to figure it out using:
[How to create an onboarding screen in SwiftUI #1 - Embedding a UIPageViewController] (https://www.blckbirds.com/post/how-to-create-a-onboarding-screen-in-swiftui-1)
I have created a wrapper that conforms to UIViewControllerRepresentable. I have created a UIViewController which contains a UIScrollView that has paging enabled.
The custom wrapper works as it should.
SwiftyUIScrollView(.horizontal, pagingEnabled: true) {
NavigationLink(destination: Text("This is a test")) {
Text("Navigation Link Test")
}
}
This button appears disabled and greyed out. Clicking it does nothing. However, if the same button is put inside a ScrollView {} wrapper, it works.
What am I missing here. Here is the custom scrollview class code:
enum DirectionX {
case horizontal
case vertical
}
struct SwiftyUIScrollView<Content: View>: UIViewControllerRepresentable {
var content: () -> Content
var axis: DirectionX
var numberOfPages = 0
var pagingEnabled: Bool = false
var pageControlEnabled: Bool = false
var hideScrollIndicators: Bool = false
init(axis: DirectionX, numberOfPages: Int, pagingEnabled: Bool,
pageControlEnabled: Bool, hideScrollIndicators: Bool, #ViewBuilder content:
#escaping () -> Content) {
self.content = content
self.numberOfPages = numberOfPages
self.pagingEnabled = pagingEnabled
self.pageControlEnabled = pageControlEnabled
self.hideScrollIndicators = hideScrollIndicators
self.axis = axis
}
func makeUIViewController(context: Context) -> UIScrollViewController {
let vc = UIScrollViewController()
vc.axis = axis
vc.numberOfPages = numberOfPages
vc.pagingEnabled = pagingEnabled
vc.pageControlEnabled = pageControlEnabled
vc.hideScrollIndicators = hideScrollIndicators
vc.hostingController.rootView = AnyView(self.content())
return vc
}
func updateUIViewController(_ viewController: UIScrollViewController, context: Context) {
viewController.hostingController.rootView = AnyView(self.content())
}
}
class UIScrollViewController: UIViewController, UIScrollViewDelegate {
var axis: DirectionX = .horizontal
var numberOfPages: Int = 0
var pagingEnabled: Bool = false
var pageControlEnabled: Bool = false
var hideScrollIndicators: Bool = false
lazy var scrollView: UIScrollView = {
let view = UIScrollView()
view.delegate = self
view.isPagingEnabled = pagingEnabled
view.showsVerticalScrollIndicator = !hideScrollIndicators
view.showsHorizontalScrollIndicator = !hideScrollIndicators
return view
}()
lazy var pageControl : UIPageControl = {
let pageControl = UIPageControl()
pageControl.numberOfPages = numberOfPages
pageControl.currentPage = 0
pageControl.tintColor = UIColor.white
pageControl.pageIndicatorTintColor = UIColor.gray
pageControl.currentPageIndicatorTintColor = UIColor.white
pageControl.translatesAutoresizingMaskIntoConstraints = false
pageControl.isHidden = !pageControlEnabled
return pageControl
}()
var hostingController: UIHostingController<AnyView> = UIHostingController(rootView: AnyView(EmptyView()))
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(scrollView)
self.makefullScreen(of: self.scrollView, to: self.view)
self.hostingController.willMove(toParent: self)
self.scrollView.addSubview(self.hostingController.view)
self.makefullScreen(of: self.hostingController.view, to: self.scrollView)
self.hostingController.didMove(toParent: self)
view.addSubview(pageControl)
pageControl.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -50).isActive = true
pageControl.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
pageControl.heightAnchor.constraint(equalToConstant: 60).isActive = true
pageControl.widthAnchor.constraint(equalToConstant: 200).isActive = true
}
func makefullScreen(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),
])
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let currentIndexHorizontal = round(scrollView.contentOffset.x / self.view.frame.size.width)
let currentIndexVertical = round(scrollView.contentOffset.y / self.view.frame.size.height)
switch axis {
case .horizontal:
self.pageControl.currentPage = Int(currentIndexHorizontal)
break
case .vertical:
self.pageControl.currentPage = Int(currentIndexVertical)
break
default:
break
}
}
}
UPDATE
This is how I am using the wrapper:
struct TestData {
var id : Int
var text: String
}
struct ContentView: View {
var contentArray: [TestData] = [TestData(id: 0, text: "Test 1"), TestData(id: 1, text: "Test 2"), TestData(id: 2, text: "TEst 3"), TestData(id: 4, text: "Test 4")]
var body: some View {
NavigationView {
GeometryReader { g in
ZStack{
SwiftyUIScrollView(axis: .horizontal, numberOfPages: self.contentArray.count, pagingEnabled: true, pageControlEnabled: true, hideScrollIndicators: true) {
HStack(spacing: 0) {
ForEach(self.contentArray, id: \.id) { item in
TestView(data: item)
.frame(width: g.size.width, height: g.size.height)
}
}
}.frame(width: g.size.width)
}.frame(width: g.size.width, height: g.size.height)
.navigationBarTitle("Test")
}
}
}
}
struct TestView: View {
var data: TestData
var body: some View {
GeometryReader { g in
VStack {
HStack {
Spacer()
}
Text(self.data.text)
Text(self.data.text)
VStack {
NavigationLink(destination: Text("This is a test")) {
Text("Navigation Link Test")
}
}
Button(action: {
print("Do something")
}) {
Text("Button")
}
}.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
.background(Color.yellow)
}
}
}
The "navigation link test" button is greyed out.
I spent some time with your code. I think I understand what the problem is, and found a workaround.
The issue is, I think, that for NavigationLink to be enabled, it needs to be inside a NavigationView. Although yours is, it seems the "connection" is lost with UIHostingController. If you check the UIHostingController.navigationController, you'll see that it is nil.
The only solution I can think of, is having a hidden NavigationLink outside the SwiftyUIScrollView that can be triggered manually (with its isActive parameter). Then inside your SwiftyUIScrollView, you should use a simple button that when tapped, changes your model to toggle the NavigationLink's isActive binding. Below is an example that seems to work fine.
Note that NavigationLink's isActive has a small bug at the moment, but it will probably be fixed soon. To learn more about it: https://swiftui-lab.com/bug-navigationlink-isactive/
window.rootViewController = UIHostingController(rootView: ContentView().environmentObject(MyModel()))
import SwiftUI
class MyModel: ObservableObject {
#Published var navigateNow = false
}
struct TestData {
var id : Int
var text: String
}
struct ContentView: View {
#EnvironmentObject var model: MyModel
var contentArray: [TestData] = [TestData(id: 0, text: "Test 1"), TestData(id: 1, text: "Test 2"), TestData(id: 2, text: "TEst 3"), TestData(id: 4, text: "Test 4")]
var body: some View {
NavigationView {
GeometryReader { g in
ZStack{
NavigationLink(destination: Text("Destination View"), isActive: self.$model.navigateNow) { EmptyView() }
SwiftyUIScrollView(axis: .horizontal, numberOfPages: self.contentArray.count, pagingEnabled: true, pageControlEnabled: true, hideScrollIndicators: true) {
HStack(spacing: 0) {
ForEach(self.contentArray, id: \.id) { item in
TestView(data: item)
.frame(width: g.size.width, height: g.size.height)
}
}
}.frame(width: g.size.width)
}.frame(width: g.size.width, height: g.size.height)
.navigationBarTitle("Test")
}
}
}
}
struct TestView: View {
#EnvironmentObject var model: MyModel
var data: TestData
var body: some View {
GeometryReader { g in
VStack {
HStack {
Spacer()
}
Text(self.data.text)
Text(self.data.text)
VStack {
Button("Pseudo-Navigation Link Test") {
self.model.navigateNow = true
}
}
Button(action: {
print("Do something")
}) {
Text("Button")
}
}.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
.background(Color.yellow)
}
}
}
The other thing is your use of AnyView. It comes with a heavy performance price. It is recommended you only use AnyView with leaf views (not your case). So I did managed to refactor your code to eliminate the AnyView. See below, hope it helps.
import SwiftUI
enum DirectionX {
case horizontal
case vertical
}
struct SwiftyUIScrollView<Content: View>: UIViewControllerRepresentable {
var content: () -> Content
var axis: DirectionX
var numberOfPages = 0
var pagingEnabled: Bool = false
var pageControlEnabled: Bool = false
var hideScrollIndicators: Bool = false
init(axis: DirectionX, numberOfPages: Int,
pagingEnabled: Bool,
pageControlEnabled: Bool,
hideScrollIndicators: Bool,
#ViewBuilder content: #escaping () -> Content) {
self.content = content
self.numberOfPages = numberOfPages
self.pagingEnabled = pagingEnabled
self.pageControlEnabled = pageControlEnabled
self.hideScrollIndicators = hideScrollIndicators
self.axis = axis
}
func makeUIViewController(context: Context) -> UIScrollViewController<Content> {
let vc = UIScrollViewController(rootView: self.content())
vc.axis = axis
vc.numberOfPages = numberOfPages
vc.pagingEnabled = pagingEnabled
vc.pageControlEnabled = pageControlEnabled
vc.hideScrollIndicators = hideScrollIndicators
return vc
}
func updateUIViewController(_ viewController: UIScrollViewController<Content>, context: Context) {
viewController.hostingController.rootView = self.content()
}
}
class UIScrollViewController<Content: View>: UIViewController, UIScrollViewDelegate {
var axis: DirectionX = .horizontal
var numberOfPages: Int = 0
var pagingEnabled: Bool = false
var pageControlEnabled: Bool = false
var hideScrollIndicators: Bool = false
lazy var scrollView: UIScrollView = {
let view = UIScrollView()
view.delegate = self
view.isPagingEnabled = pagingEnabled
view.showsVerticalScrollIndicator = !hideScrollIndicators
view.showsHorizontalScrollIndicator = !hideScrollIndicators
return view
}()
lazy var pageControl : UIPageControl = {
let pageControl = UIPageControl()
pageControl.numberOfPages = numberOfPages
pageControl.currentPage = 0
pageControl.tintColor = UIColor.white
pageControl.pageIndicatorTintColor = UIColor.gray
pageControl.currentPageIndicatorTintColor = UIColor.white
pageControl.translatesAutoresizingMaskIntoConstraints = false
pageControl.isHidden = !pageControlEnabled
return pageControl
}()
init(rootView: Content) {
self.hostingController = UIHostingController<Content>(rootView: rootView)
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var hostingController: UIHostingController<Content>! = nil
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(scrollView)
self.makefullScreen(of: self.scrollView, to: self.view)
self.hostingController.willMove(toParent: self)
self.scrollView.addSubview(self.hostingController.view)
self.makefullScreen(of: self.hostingController.view, to: self.scrollView)
self.hostingController.didMove(toParent: self)
view.addSubview(pageControl)
pageControl.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -50).isActive = true
pageControl.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
pageControl.heightAnchor.constraint(equalToConstant: 60).isActive = true
pageControl.widthAnchor.constraint(equalToConstant: 200).isActive = true
}
func makefullScreen(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),
])
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let currentIndexHorizontal = round(scrollView.contentOffset.x / self.view.frame.size.width)
let currentIndexVertical = round(scrollView.contentOffset.y / self.view.frame.size.height)
switch axis {
case .horizontal:
self.pageControl.currentPage = Int(currentIndexHorizontal)
break
case .vertical:
self.pageControl.currentPage = Int(currentIndexVertical)
break
default:
break
}
}
}
The above solution works if we are not required to navigate to different screens from the content of scroll view. However, if we need a navigation link onto the scroll content instead of the scroll view itself, then the below code would work perfectly.
I was into a similar problem. I have figured out that the problem is with the UIViewControllerRepresentable. Instead use UIViewRepresentable, although I am not sure what the issue is. I was able to get the navigationlink work using the below code.
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
}
}
Then create a new class to handle the delegates of a scrollview. You can include the below code into the UIViewRepresentable as well. But I prefer keeping it separated for a clean code.
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)
}
}
Now to implement the scrollView use the below code.
#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
}
I had this same issue and tried lots of different solutions. The navigation link had been working and stopped. putting the view inside a navigation view worked.
In the example, masterview() contains the navigation links that did not work and now do.
struct ContentView: View {
var body: some View {
NavigationView {
MasterView()
//SettingsView()
//DetailView()
//newviewcontroller()
}.navigationViewStyle(DoubleColumnNavigationViewStyle())
}
}