I have a situation where I'm using a UIScrollView to help users with smaller phones see the full text inside a window. And I was wanting to show an image icon if they needed to scroll (just so that they know there is more inside the window) but I'm having a problem finding the height of the scrollview using Swift.
This is the hierarchy of my objects
Basically, those 4 labels fit inside a 4.7" iPhone but not the 4" iPhone. I tried setting some logic to check if the UIScrollView content is larger than the window, but it doesn't seem to be working. I keep getting that the height is zero.
I'm using scrollHeight = scrollView.contentSize.height and have tried putting that inside of viewDidLoad(), viewWillAppear(), and viewDidLayoutSubviews() but every time it ends up being 0.
Is contentSize the right thing I should be using to check the height?
TL;DR;
As a general guide, Auto Layout does not finish giving views their size by the time viewDidLoad is called (neither is it correct inside viewDidLayoutSubviews). To make sure all views and their subviews have their correct sizes before querying their bounds or frame, do:
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
print(self.someSubview.frame) // gives correct frame
Explanation
Somewhat counterintuitively, putting your code inside viewDidLayoutSubviews does not mean all sub-views have been given their correct size by Auto Layout. To quote the docs for this method:
However, this method being called does not indicate that the individual layouts of the view's subviews have been adjusted.
What this means is that: inside viewDidLayoutSubviews, only the first hierarchical-level of sub-views will have their correct size (i.e. child views but not "grandchild views").
Here is an example layout I created (the red view is the child, the blue view is the grandchild).
A few important points about this example:
All views are positioned using Auto Layout constraints to their parent view (fixed margins, but not fixed widths), this allows them to grow or shrink depending on the screen size of the simulator I run this on.
I've used an iPhone 7 sized view controller in my storyboard, and ran the example on an iPhone 7 Plus Simulator. This means I can be sure the views will grow somewhat and use this to determine whether or not a view has its original size or its final size.
Note that in Interface Builder, the original width of the child view (red) is 240 points and the original width of the grandchild view (blue) is 200 points.
And here is the code:
class ViewController: UIViewController {
#IBOutlet weak var childView: UIView!
#IBOutlet weak var grandchildView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
print("child ", #function, childView.frame.size.width)
print("grandchild", #function, grandchildView.frame.size.width)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
print("child ", #function, childView.frame.size.width)
print("grandchild", #function, grandchildView.frame.size.width)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("child ", #function, childView.frame.size.width)
print("grandchild", #function, grandchildView.frame.size.width)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print("child ", #function, childView.frame.size.width)
print("grandchild", #function, grandchildView.frame.size.width)
}
}
And here is the output:
child viewDidLoad() 240.0
grandchild viewDidLoad() 200.0
child viewWillAppear 240.0
grandchild viewWillAppear 200.0
child viewDidLayoutSubviews() 271.0 // `child` has it's final width now
grandchild viewDidLayoutSubviews() 200.0 // `grandchild` still has it's original width!
// By now, in MOST cases, all views will have their correct sizes.
child viewDidAppear 271.0
grandchild viewDidAppear 231.0
What you can see from this output is that viewDidLayoutSubviews does not guarantee that anything past the immediate sub-views of the View Controller's principal view have their correct size.
Note: Usually by the time viewDidAppear is called, views have their correct size, but I'd say this is by no means guaranteed.
Related
I have a UIViewRepresentable that represents a PKCanvasView.
struct PKCanvasRepresentable : UIViewRepresentable
{
#Binding var canvas: PKCanvasView
func makeUIView(context: Context) -> PKCanvasView {
canvas.tool = PKInkingTool(.pen, color: .black, width: 2)
canvas.drawingPolicy = .anyInput
canvas.isOpaque = false
canvas.backgroundColor = .clear
return canvas
}
func updateUIView(_ uiView: PKCanvasView, context: Context) {}
}
I want to use it as part of a sheet, that contains other input components and must be vertically scrollable.
#State var canvas = PKCanvasView()
var body: some View {
NavigationView {
ScrollView {
VStack {
// ..various components..
PKCanvasRepresentable(canvas: $canvas)
}
}
}
}
The drawing does not work, because the drawing gesture gets canceled by the scroll gesture.
I would like the PKCanvasView related gestures having priority over the scroll view ones. How can i achieve this?
Example
The expected behaviour can be seen when - for example - a DatePicker in wheel style is in a ScrollView. The scroll view does not receive any gesture input when interacting with the DatePicker. I would like to have the same behaviour for a PKCanvasView.
Additional info
I tried to add various Gesture modifiers to the Representable which prevents the ScrollView from getting input events - but of course that also prevents the Canvas from getting user input.
I built a drawing component myself in the past which worked, because i had control over the Gestures that were added to make the component happen. But i would prefer to use PKCanvasView, which does everything i need already - except from the described issue.
I saw this question - but it has nothing to do with PKCanvasView and its solution does not help.
I tried ai based code generators - but i don't have any subscriptions so i'm limited in tries and length of the answer. I tried the following quote, which produced only invalid, tutorial level answers:
Write a SwitUI view that contains of a ScrollView which has a nested UIViewRepresentable of a PKCanvasView where the ScrollView does not receive any kind of user input, events or gestures while the user interacts with the PKCanvasView and tries to draw but functions normally whenever the user does not interact with the PKCanvasView
So for my own reasons, I need the full control that UITextField and its delegates would normally offer, but the screen it's being added to is written with SwiftUI. Needs a .decimal keyboard, so no Return Key.
I have only 2 issues remaining, 1 of which I hope to resolve here. Attempting to add a call to resign first responder and add it to a VStack on the page basically disables the UITextField, since I can't bring up the keyboard.
How can I dismiss this keyboard without adding an arbitrary extra button to the page?
Example Code:
Struct CustomTextView: UIViewRepresentable {
/// Insert init, updateView, binding variable, coordinator, etc
func makeView() -> UITextField {
var textField = UITextField()
textField.delegate = context.coordinator
/// Set up rest of textfield parameters such as Font, etc.
return textField
}
}
extension CustomTextView {
class Coordinator: NSObject, UITextFieldDelegate {
/// UITextfield delegate implementations, extra reference to binding variable, etc
/// Primarily textField.shouldChangeCharactersInRange
}
}
struct ContentView: View {
#State viewModel: ViewModel
var body: some View {
VStack {
CustomTextView($viewModel.parameter)
/// Other views
}
.onTap {
/// Attempting to add the generic call to UIApplication for resignFirstResponder here does not allow CustomTextView to ever hold it even when tapped in
}
}
}
I can't give all the code for privacy reasons, but this should be enough to establish my issue.
I have done this by adding this Function to you view below.
func hideKeyboard() {
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
Then with a ontapGesture you can make the keyboard go away.
For example you can use this on the background Stack of your whole view. If a user taps on the background the keyboard will dissapear.
.onTapGesture {
self.hideKeyboard()
}
So I found a trick on my own with an epiphany overnight.
First, I would like to share to anyone else a very basic reason why inb4cookies solution wasn't quite adequate. While I had already tried adding a resignFirstResponder call like it to the onTap of the background stack, it was triggering the onTap for the VStack when I was clicking the field.
This is likely because I am using a UITextField as the back end for this component and not a SwiftUI TextField.
However, it was partially used in the final solution. I still applied it, but there is an extra step.
VStack {
CustomTextView($viewModel.parameter)
.onTap {/*Insert literally any compiling code here*/ }
/// Other views
}
.onTap {
self.hideKeyboard()
}
You'll see that above, there is an extra onTap. I tested it with a print statement, but this will override the onTap for the VStack and prevent the keyboard from being dismissed right after it is brought up. Tapping anywhere else on the VStack still closes it, except for Buttons. But I can always add hideKeyboard to those buttons if needed.
I am showing a UIViewController via a SwiftUI view, like so:
#available(iOS 13, *)
struct WelcomeNavView: UIViewControllerRepresentable {
func makeUIViewController(context: UIViewControllerRepresentableContext<WelcomeNavView>) -> UINavigationController {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let navVc = storyboard.instantiateViewController(withIdentifier: "welcomeNav") as! UINavigationController
return navVc
}
func updateUIViewController(_ uiViewController: UINavigationController, context: UIViewControllerRepresentableContext<WelcomeNavView>) {
}
}
I then present it from a ViewController like so:
self.viewController?.present(style: .fullScreen) {
WelcomeNavView()
}
However, it does not occupy the entire screen and the UIHostViewController color is showing at the top and bottom:
How can I change the color of the UIHostingViewController's view.. Or expand the View it is holding to occupy the entire screen?
Another simple and quick solution is, you can ignore safe area of your WelcomeNavView() while presenting.
example
iOS 13:
WelcomeNavView().edgesIgnoringSafeArea(.all)
iOS 14 and above:
WelcomeNavView().ignoresSafeArea()
Here is the solution,
I ran into similar problem, wherein I had to set hosting view controller's background clear.
Apparently, rootView (probably our SwiftUI View) of hostingVC and hostingVC.view are different.
so this would allow you to change to background color.
hostingVC.view.backgroundColor = .clear
Of course use any color in place of ".clear".
Just keep in mind to change color of SwiftUI view passed as rootView to hostingVC accordingly, mostly make that clear, so it won't be shown against above set color.
Your_SwiftUI_View.background(Color.clear)
I currently have several labels and buttons in a UIView. I am using Storyboards and I want to add an image to the background. I tried it this way:
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(patternImage: UIImage(named:"background.png")!)
But unfortunately, this does not look right in the larger screen sizes. I think that I need to add a UIImageView. When I added a UIImageView, I couldn't figure out how to set it to be in the background so my button and labels could still be seen.
let someImageView: UIImageView = {
let theImageView = UIImageView()
theImageView.image = UIImage(named: "yourImage.png")
return theImageView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(someImageView) //This add it the view controller without constraints
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
someImageView.frame = view.bounds
}
In your storyboard:
1- Add a UIImageView (inside your main view and outside everything else) and set its image to the image you want.
2- setup its constraints properly to fill the screen (give it 0 from all sides).
3- From attribute inspector, set Content Mode property to Aspect Fit.
I solved this problem by going to the panel in Storyboards and moving the UIImageView above the container view that held the labels and buttons. The UIImageView remained inside of the View, but moved to the background (under the buttons and labels).
I'm having a problem in Swift 3.0 right now.
As attached picture (a), I embedded navigationController into ViewController.swift. ViewController.swift have button to connect to UITableCell MovementStatusVC.swift. And MovementDetailsVC.swift is to display all value from table cell.
The problem that i'm facing right now is when I create button in MovementDetailsVC.swift and perform segue to pass the data inside "EditData" function, Page display twice.
MovementDetailsVC.swift
import UIKit
class MovementDetailsVC: UIViewController {
#IBAction func EditData(_ sender: Any) {
performSegue(withIdentifier: "EditMovementDetails", sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
The EditMovementDetailsVC.swift controller display twice when I tap Edit button in MovementDetailsVC.swift as shown as in picture below.
I'm using perform segue and prepare segue in MovementDetailsVC.swift
How to fix it so the view only perform one time ?
Thanks.