screen freezes if using modalPresentationStyle = .overCurrentContext swift 5 - swift

I am presenting a navigation controller with modalPresentationStyle as overCurrentContext. After dismissing controller screen freezes.
I am presenting a FirstViewController with NAvigationController.
let firstVC = FirstViewController.controller()
let nvc = UINavigationController(rootViewController: firstVC)
nvc.modalPresentationStyle = .overCurrentContext
present(nvc, animated: true)
Then inside FirstViewController, I am passing navigationController to push SecondViewController
override func viewDidLoad() {
super.viewDidLoad()
guard let nav = navigationController else { return }
showSecondViewController(parentController: nav)
}
func showSecondViewController(parentController: UINavigationController) {
let secondVC = SecondViewController.controller()
parentController.pushViewController(secondVC, animated: true)
}
Now first I am popping SecondViewcontroller on click action from SecondViewController
navigationController?.popViewController(animated: animated)
Then with some call back I am dismissing FirstViewController and NavigationControoler (nvc)
self.controller?.dismiss(animated: true)
self.nvc?.dismiss(animated: true)
Now after dismissing as above I am facing screen freeze issue.
I need help to resolve this issue. Please help. Why screen is freezing.
Please let me know if I am missing anything here?
Thanks

Did you see any errors in the console? I'm not clear about "some call back" as you mentioned above. Can you elaborate?
I created a small project to replicate your issue. The approach below works fine in my case
ViewController is the root view controller
FirstViewController is the first controller presented on top of ViewController
SecondViewController is pushed from the first view controller after the event "ViewDidLoad" happens in FirstViewController
I also created 1 onViewControllerDissmied callback in each ViewControllers (especially FirstViewController and SecondViewController)
In ViewController - I created a touch up inside event as below
#objc func onButtonClicked() {
let firstVC = FirstViewController()
nvc = UINavigationController(rootViewController: firstVC)
guard let nvc = nvc else { return }
nvc.modalPresentationStyle = .overCurrentContext
present(nvc, animated: true)
mycontroller = firstVC
firstVC.onViewControllerDimissed = { [weak self] in
self?.mycontroller?.dismiss(animated: true)
self?.nvc?.dismiss(animated: true)
}
}
FirstViewController
class FirstViewController: UIViewController {
var label: UILabel = {
let button = UILabel()
button.translatesAutoresizingMaskIntoConstraints = false
button.text = "First View Controller"
button.textColor = .white
return button
}()
var onViewControllerDimissed: (() -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .purple
guard let nav = navigationController else { return }
showSecondViewController(parentController: nav)
}
func showSecondViewController(parentController: UINavigationController) {
let secondVC = SecondViewController()
parentController.pushViewController(secondVC, animated: true)
secondVC.onViewControllerDimissed = { [weak self] in
self?.onViewControllerDimissed?()
}
}
}
SecondViewController
class SecondViewController: UIViewController {
var label: UILabel = {
let button = UILabel()
button.translatesAutoresizingMaskIntoConstraints = false
button.text = "Second View Controller"
return button
}()
var onViewControllerDimissed: (() -> Void)?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let position = touch.location(in: view)
let pnt: CGPoint = CGPoint(x: position.x, y: position.y)
if (view.bounds.contains(pnt)) {
onScreenTouch()
}
}
}
func onScreenTouch() {
navigationController?.popViewController(animated: true)
onViewControllerDimissed?()
}
}

Related

Problem with delegates removing annotation

I have two screens. The first one (firstViewController) has a mapView with a UITapGestureRecognizer. When the user taps the screen, an annotations is added to the map and the second screen (secondViewController) is presented.
When the user dismisses the secondViewController and comes back to the first one, the annotation should be removed. I know I have to use delegation, but I just can't make it to work.
This is the code I have now:
class firstViewController: UIViewController, AnnotationDelegate {
let mapView = MKMapView()
var temporaryPinArray = [MKPointAnnotation]()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(mapView
let gesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
mapView.addGestureRecognizer(gesture)
secondVC.annotationDelegate = self
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
mapView.frame = view.bounds
}
#objc func handleTap(_ gestureReconizer: UILongPressGestureRecognizer) {
let location = gestureReconizer.location(in: mapView)
let coordinates = mapView.convert(location, toCoordinateFrom: mapView)
mapView.removeAnnotations(mapView.annotations)
let pin = MKPointAnnotation()
pin.coordinate = coordinates
temporaryPinArray.removeAll()
temporaryPinArray.append(pin)
mapView.addAnnotations(temporaryPinArray)
// Present secondViewController
let secondVC = SecondViewController()
panel.set(contentViewController: secondVC)
panel.addPanel(toParent: self)
}
func didRemoveAnnotation(annotation: MKPointAnnotation) {
mapView.removeAnnotation(annotation)
}
}
Second View Controller
protocol AnnotationDelegate {
func didRemoveAnnotation(annotation: [MKPointAnnotation])
}
class SecondViewController: UIViewController {
var annotationDelegate: AnnotationDelegate!
let mainVC = firstViewController()
let closeButton: UIButton = {
let button = UIButton()
button.backgroundColor = .grey
button.layer.cornerRadius = 15
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(closeButton)
closeButton.addTarget(self, action: #selector(dismissPanel), for: .touchUpInside)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
closeButton.frame = CGRect(x: view.frame.width-50, y: 10, width: 30, height: 30)
}
#objc func dismissPanel() {
self.dismiss(animated: true, completion: nil)
annotationDelegate.didRemoveAnnotation(annotation: mainVC.temporaryPinArray)
}
}
Thank you so much for your help!
You created a new instance of firstViewController inside SecondViewController. This instance is unrelated to the actual first one:
let mainVC = firstViewController()
This means that temporaryPinArray is different as well. So instead of passing in this unrelated array...
#objc func dismissPanel() {
self.dismiss(animated: true, completion: nil)
annotationDelegate.didRemoveAnnotation(annotation: mainVC.temporaryPinArray)
}
Just change the function to take no parameters instead:
protocol AnnotationDelegate {
func didRemoveAnnotation() /// no parameters
}
#objc func dismissPanel() {
self.dismiss(animated: true, completion: nil)
annotationDelegate.didRemoveAnnotation() /// no parameters
}
And inside firstViewController's didRemoveAnnotation, reference the actual temporaryPinArray.
func didRemoveAnnotation() {
mapView.removeAnnotations(temporaryPinArray) /// the current array
}

iOS 13 - Right Bar Button Item goes offset in Modal Sheet presentation

I have this strange problem with iOS 13 and its new sheet cards style modal presentation.
From ViewController1 I modal present ViewController2 embedded in a NavigationController, and everything works fine.
From ViewController2, I then modal present ViewController3 embedded in a NavigationController, and I get the Right Bar Button offset.
Here is a video of the problem: does anybody have a fix?
Main View Controller
import UIKit
let vc1identifier = "vc1identifier"
let vc2identifier = "vc2identifier"
class ViewController: UIViewController {
#IBAction func tap1(_ sender: UIButton) {
if let navigation = self.storyboard?.instantiateViewController(withIdentifier: vc1identifier) as? UINavigationController,
let nextVC = navigation.contentViewController as? UnoViewController {
//self.navigationController?.pushViewController(nextVC, animated: true)
self.present(navigation, animated: true, completion: nil)
}
}
}
extension UIViewController {
var contentViewController: UIViewController {
if let navcon = self as? UINavigationController {
return navcon.visibleViewController!
} else {
return self
}
}
}
Second View Controller
import UIKit
class UnoViewController: UIViewController {
#IBOutlet weak var barButton: UIBarButtonItem!
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
barButton.title = "GotoVC2"
}
#IBAction func pressThis(_ sender: UIBarButtonItem) {
if let navigation = self.storyboard?.instantiateViewController(withIdentifier: vc2identifier) as? UINavigationController,
let nextVC = navigation.contentViewController as? DueViewController {
self.present(navigation, animated: true, completion: nil)
}
}
}
I came across the same issue.
Solution is easy, you just need to tell navigationbar it needs layout like this
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if #available(iOS 13.0, *) {
navigationController?.navigationBar.setNeedsLayout()
}
}

Call a View from another ViewController Swift

I have a ViewController that has a UIView set on top of it and a button that opens a popover to another ViewController. I want a button on the popover view controller to set the UIView to disable. How do I reference the UIView from the first view controller from a button in the second view controller?
EDIT:
Below is code that I use to call the popover view controller. Notice how I call dimView.isHidden = false from this first viewcontroller. I want to run dimView.isHidden = true from the popover view controller.
let popover = storyboard?.instantiateViewController(withIdentifier: "PopoverVC")
popover?.modalPresentationStyle = .popover
popover?.popoverPresentationController?.delegate = self as? UIPopoverPresentationControllerDelegate
popover?.popoverPresentationController?.sourceView = self.view
popover?.popoverPresentationController?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
popover?.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
dimView.isHidden = false
self.present(popover!, animated: false)
EDIT 2:
Below is my popover view controller. Since it is not called PopoverVC. I updated the answer to include let popover = storyboard?.instantiateViewController(withIdentifier: "PopoverVC") as! PopOverViewController but still no luck.
import UIKit
var parentController:UIViewController?
class PopOverViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func closeButton(_ sender: Any) {
self.dismiss(animated: false, completion: nil)
}
}
EDIT 3:
class ViewController: FormViewController {
override func viewWillAppear(_ animated: Bool) {
dimView.isHidden = true
}
#IBOutlet weak var dimView: UIView!
You can pass a reference to your current view controller when presenting your PopoverVC and then you can access its view from PopoverVC. Just create a property in PopoverVC that can store the reference, like var parentController:UIViewController?
let popover = storyboard?.instantiateViewController(withIdentifier: "PopoverVC") as! PopoverViewController
popover?.modalPresentationStyle = .popover
popover?.popoverPresentationController?.delegate = self as? UIPopoverPresentationControllerDelegate
popover?.popoverPresentationController?.sourceView = self.view
popover?.popoverPresentationController?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
popover?.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
popover?.dimView = self.dimView
dimView.isHidden = false
self.present(popover!, animated: false)
PopOverViewController:
class PopOverViewController: UIViewController {
var dimView:UIView?
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func closeButton(_ sender: Any) {
self.dismiss(animated: false, completion: nil)
}
}

loading childViewControllers first time logging in

I have been struggling with an issue for loading child ViewControllers. The first time I log in it shows the containerView but without the childViewControllers loaded. When I close the app and re-open the app with the logged in state saved the childViews in the containerView are displayed. I know it has something to do with my window hierarchy and rootviewController. I have researched this a bunch but still am having issues solving. Thanks in advance!
// app delegate
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
window?.rootViewController = MainNavigationController()
return true
}
// mainNavigationController - RootViewController
class MainNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
let vc1 = TravelersFeedVC()
let vc2 = ProfileVC()
if isLoggedIn() {
// assume user is logged in
let homeController = HomeController()
homeController.firstViewController = vc1
homeController.secondViewController = vc2
viewControllers = [homeController]
} else {
perform(#selector(showLoginController), with: nil, afterDelay: 0.01)
}
}
fileprivate func isLoggedIn() -> Bool {
return UserDefaults.standard.isLoggedIn()
}
func showLoginController() {
let loginController = LoginController()
present(loginController, animated: true, completion: {
// perhaps do something here later
})
}
}
// log in function
func finishLoggingIn() {
let rootViewController = UIApplication.shared.keyWindow?.rootViewController
guard let mainNavigationController = rootViewController as? MainNavigationController else { return }
mainNavigationController.viewControllers = [HomeController()]
let vc1 = TravelersFeedVC()
let vc2 = ProfileVC()
let homeController = HomeController()
homeController.firstViewController = vc1
homeController.secondViewController = vc2
UserDefaults.standard.setIsLoggedIn(value: true)
dismiss(animated: true, completion: nil)
}
// HomeController
class HomeController: UIViewController, FBSDKLoginButtonDelegate {
// child view controllers to put inside content view
var firstViewController: TravelersFeedVC?
var secondViewController: ProfileVC?
private var activeViewController: UIViewController? {
didSet {
removeInactiveViewController(inactiveViewController: oldValue)
updateActiveViewController()
}
}
private func removeInactiveViewController(inactiveViewController: UIViewController?) {
if let inActiveVC = inactiveViewController {
// call before removing child view controller's view from hierarchy
inActiveVC.willMove(toParentViewController: nil)
inActiveVC.view.removeFromSuperview()
// call after removing child view controller's view from hierarchy
inActiveVC.removeFromParentViewController()
}
}
private func updateActiveViewController() {
if let activeVC = activeViewController {
// call before adding child view controller's view as subview
addChildViewController(activeVC)
activeVC.view.frame = contentView.bounds
contentView.addSubview(activeVC.view)
// call before adding child view controller's view as subview
activeVC.didMove(toParentViewController: self)
}
}
// UI elements
lazy var contentView: UIView = {
let tv = UIView()
tv.backgroundColor = UIColor.blue
tv.translatesAutoresizingMaskIntoConstraints = false
tv.layer.masksToBounds = true
return tv
}()
var segmentedController: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
activeViewController = firstViewController
checkIfUserIsLoggedIn()
view.addSubview(contentView)
setupProfileScreen()
let items = ["Travelers", "Me"]
segmentedController = UISegmentedControl(items: items)
navigationItem.titleView = segmentedController
segmentedController.tintColor = UIColor.black
segmentedController.selectedSegmentIndex = 0
// Add function to handle Value Changed events
segmentedController.addTarget(self, action: #selector(HomeController.segmentedValueChanged(_:)), for: .valueChanged)
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Sign Out", style: .plain, target: self, action: #selector(handleSignOut))
navigationItem.leftBarButtonItem?.tintColor = UIColor.black
}
// reference to collectionViewController
var travelersFeedVC: TravelersFeedVC!
func segmentedValueChanged(_ sender:UISegmentedControl!)
{
switch segmentedController.selectedSegmentIndex {
case 0:
activeViewController = firstViewController
case 1:
activeViewController = secondViewController
default: // Do nothing
break
}
}
In your finishLoggingIn() it looks like you are using 2 separate HomeController instances.
Something like this should fix it.
func finishLoggingIn() {
let rootViewController = UIApplication.shared.keyWindow?.rootViewController
guard let mainNavigationController = rootViewController as? MainNavigationController else { return }
// create it
let homeController = HomeController()
// use it
mainNavigationController.viewControllers = [homeController]
let vc1 = TravelersFeedVC()
let vc2 = ProfileVC()
// use it again
homeController.firstViewController = vc1
homeController.secondViewController = vc2
UserDefaults.standard.setIsLoggedIn(value: true)
dismiss(animated: true, completion: nil)
}

How add tabs programmatically in UITabBarController with swift?

How to create programmatically tabs from any class extended by UIViewController:
class DashboardTabBarController: UITabBarController {
override func viewDidLoad() {
//here
}
...
}
UPDATE SWIFT 5
One example of how to create an UITabBarController programmatically could be like this:
First we create the UIViewControllers that will be the content for each tab of the tab bar interface. For this example we only create one very simple.
class Item1ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.green
self.title = "item1"
print("item 1 loaded")
}
}
Now, the UITabBarController:
We create the new instances of the UIViewControllers that we want to display in the tab bar. Then we create an icon for each instance we have created and then we create an array that contains all UIViewControllers that specify the content for each tab of the tab bar interface. The order of the view controllers in the array corresponds to the display order in the tab bar.
class DashboardTabBarController: UITabBarController, UITabBarControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let item1 = Item1ViewController()
let icon1 = UITabBarItem(title: "Title", image: UIImage(named: "someImage.png"), selectedImage: UIImage(named: "otherImage.png"))
item1.tabBarItem = icon1
let controllers = [item1] //array of the root view controllers displayed by the tab bar interface
self.viewControllers = controllers
}
//Delegate methods
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
print("Should select viewController: \(viewController.title ?? "") ?")
return true;
}
}
If you are using storyboard for the viewcontrollers then you have to write like this in your tabbarcontroller class.
class CustomTabbarController : UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let firstViewController = FirstViewController()
let navigationController = UINavigationController(rootViewController: firstViewController)
navigationController.title = "First"
navigationController.tabBarItem.image = UIImage.init(named: "map-icon-1")
viewControllers = [navigationController]
if let secondViewController = storyboard.instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController {
let navgitaionController1 = UINavigationController(rootViewController: secondViewController)
navgitaionController1.title = "Second"
navgitaionController1.tabBarItem.image = UIImage.init(named: "second-icon-1")
var array = self.viewControllers
array?.append(navgitaionController1)
self.viewControllers = array
}
}
}
private lazy var tabbarViewController: UITabBarController = {
let tabbarViewController = UITabBarController()
tabbarViewController.setViewControllers([startVC,
offerVC,
benefitsVC,
shopVC,
recipesVC], animated: true)
return tabbarViewController
}()
window?.rootViewController = tabbarViewController