navigationBar .tintColor with UIDocumentPickerViewController (Document Picker)? - ios

I am using Swift 2 in Xcode 7.0 beta 6
Long story short, I am trying to work out how to set .navigationBar.barStyle and navigationBar.tintColor when using a document picker to access iCloud - i.e. a UIDocumentPickerViewController.
I have tried e.g. :
/...
documentPicker.navigationController!.navigationBar.barStyle = UIBarStyle.Default
documentPicker.navigationController!.navigationBar.tintColor = UIColor.orangeColor()
/...
For example. Here I have a view controller embedded within a navigation controller:
In MyNavigationController I can set the .barStyle and .tintStyle as follows:
class MyNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationBar.barStyle = UIBarStyle.Default
self.navigationBar.tintColor = UIColor.orangeColor()
}
}
So .tintStyle is orange as follows:
iCloud is enabled and FirstViewController conforms to UIDocumentPickerDelegate. The bar button calls an IBAction function as shown here in the code for FirstViewController:
class FirstViewController: UIViewController, UIDocumentPickerDelegate {
// ...
#IBAction func importDocument(sender: UIBarButtonItem) {
let documentPicker: UIDocumentPickerViewController = UIDocumentPickerViewController(documentTypes: ["public.text"], inMode: UIDocumentPickerMode.Import)
documentPicker.delegate = self
documentPicker.modalPresentationStyle = UIModalPresentationStyle.FullScreen
documentPicker.popoverPresentationController?.barButtonItem = sender
self.presentViewController(documentPicker, animated: true, completion: nil)
}
func documentPicker(controller: UIDocumentPickerViewController, didPickDocumentAtURL url: NSURL) {
// ...
}
func documentPickerWasCancelled(controller: UIDocumentPickerViewController) {
// ...
}
}
That works. The document picker loads as expected:
BUT. For the sake of working out how to do this, I want the menu item "Done" to be orange. Like the previous.
I have tried adding the following code to the #IBAction as follows:
//...
documentPicker.navigationController!.navigationBar.barStyle = UIBarStyle.Default
documentPicker.navigationController!.navigationBar.tintColor = UIColor.orangeColor()
self.presentViewController(documentPicker, animated: true, completion: nil)
//...
That doesn't work because at this point documentPicker.navigationController is nil.
Can anyone tell me how or where in the cycle I can access documentPicker.navigationController!.navigationBar.tintColor?
Or perhaps I am missing something and there is some other way of changing the menu color?
Or perhaps I should be looking to create a custom navigation controller - and a custom document picker view controller. Then in theory I would be able to access a relevant viewDidLoad. I tried that but realised that I would then also need a custom version of the UIDocumentPickerDelegate protocol. There must surely be an easier solution (and I had doubts as to whether that would be allowed).

You can alter navigationBar default tint color via UIAppearance:
UINavigationBar.appearance().tintColor = UIColor.orangeColor()

swift 3,4 and xcode 9+ :
documentPicker.view.tintColor = .orange

Related

How to implement a SearchController with a SearchResultsController

Hello I am trying to implement a SearchController into my application however, my application has different tabs in which I would like them to see the search functionality. I have added a button to the NavBar and each of these tabs has a main controller view which includes this code. Unfortunately when I try to search for something the table view does not display with the results. Thank you for your help! Please find the code below:
MainController:
// set up search:
func setUpSearch(){
self.searchDataSource = DataTableViewController() // UIViewController, contains all functions for tableview plus outlet of tableview
self.searchController = UISearchController.init(searchResultsController: searchDataSource)
self.searchController?.searchBar.delegate = self
self.searchController?.searchBar.showsCancelButton = true
self.searchController?.searchBar.placeholder = "Search for people or places"
}
// user clicked on search button:
func searchButtonClicked(){
self.searchController?.isActive = true
self.searchController?.searchBar.becomeFirstResponder()
if let controller = self.searchController {
present(controller, animated: true, completion: nil)
}
}

Popover presentation style on iPhone devices - possible any more?

I'm trying to define a popover view attached to a view like this:
Here's my code:
class MyController: UIViewController, UIPopoverPresentationControllerDelegate {
...
func displaySignOut(_ sender: UIButton) {
let vc = UIStoryboard(name: "Main", bundle: nil)
.instantiateViewController(withIdentifier: "signOutPopover")
vc.modalPresentationStyle = .popover
vc.preferredContentSize = CGSize(width: 100, height: 30)
present(vc, animated: true, completion: nil)
let pc = vc.popoverPresentationController!
pc.sourceView = sender
pc.sourceRect = sender.bounds
pc.delegate = self
}
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return .none
}
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
}
Because the popover is so small, I'd like to use this style on all devices. I've followed the usual advice (e.g., here) on overriding adaptivePresentationStyle to return UIModalPresentationStyle.none.
This works fine on iPad devices, but on iPhones, it doesn't. On smaller iPhone devices, it comes up full screen all the time. On larger screens (e.g., iPhone 7 Plus), it comes up wrong, but, weirdly, switches to a popover presentation (in both portrait and landscape) if I rotate the device after the popover appears. (If I dismiss the popover and bring it up again, it's wrong again until I rotate the device.) Furthermore, in landscape it comes up in a strange configuration (not full screen as in portrait):
Unlike with a popover presentation, this does not dismiss if I tap outside the popover view itself.
The Apple documentation says (in part):
In a horizontally compact environment, popovers adapt to the UIModalPresentationOverFullScreen presentation style by default.
The "by default" strongly suggests that there's a way to override this behavior. But (as is consistent with this post), overriding adaptivePresentationStyle in the delegate doesn't seem to be the way to do this any more (although it used to work). So is there a new way to modify the default behavior?
I'm using XCode 8.3.3 and Swift 3.1, targeting iOS 9+.
I have created one custom class with storyboard inside that connect
outlet of button and implemented below code.
import UIKit
class PopOverViewController: UIViewController {
#IBOutlet weak var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
button.backgroundColor = UIColor.purple
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Updating the popover size
override var preferredContentSize: CGSize {
get {
let size = CGSize(width: 80, height: 60)
return size
}
set {
super.preferredContentSize = newValue
}
}
//Setup the ViewController for popover presentation
func updatePopOverViewController(_ button: UIButton?, with delegate: AnyObject?) {
guard let button = button else { return }
modalPresentationStyle = .popover
popoverPresentationController?.permittedArrowDirections = [.any]
popoverPresentationController?.backgroundColor = UIColor.purple
popoverPresentationController?.sourceView = button
popoverPresentationController?.sourceRect = button.bounds
popoverPresentationController?.delegate = delegate
}
}
And then Inside ViewController implemented one function to show
popOver on iphone
func showPopOver(button: UIButton!) {
let viewController = PopOverViewController()
viewController.updatePopOverViewController(button, with: self)
present(viewController, animated: true, completion: nil)
}
Note:- Tested and this should work on Portrait as well Landscape mode
iOS 15 has some new ways to solve this problem.
Take a look at the WWDC21 Session "Customize and Resize Sheets in UIKit" https://developer.apple.com/wwdc21/10063
Pretty simple new interface for popovers and customized sheets. Shows how to do non-modal interaction with pop over and the view behind it.

SFSafariViewController loading blank white page

I am using SFSafariViewController to open a URL in my iOS app.. it was working perfectly on iOS 9 but after updating my device to iOS 10, it just loads a blank white page with no URL in the address bar. Even safariViewController(controller: SFSafariViewController, didCompleteInitialLoad didLoadSuccessfully: Bool) is not getting called after controller is presented.
I have imported this in the view controller:
import SafariServices
code:
let url = NSURL(string: urlString)!
if #available(iOS 9.0, *) {
let safariVC = SFSafariViewController(URL: url)
safariVC.delegate = self
self.presentViewController(safariVC, animated: true, completion: {
self.hideHUD()
})
} else {
// Fallback code
}
here is the link to exact same problem someone else faced
Try commenting out any loading animations you are doing and try without that.
...
// self.showHUD()
// self.hideHUD()
...
Its because of a bug in iOS 10 introduced during a security fix which doesn't let safariViewController load when using progress bars and loaders added as a window above the main window
I really wish Apple had documented the change.
I had to comment out the loading indicator in my current app to get it working.
Came across this as seeing some similar problems that I was seeing when trying to use a SafariViewController. Tracked my problems down to using SafariViewController when a popup was present. Have put together some code to show my problem and possible solution.
ViewController.swift:
/*
This view controller tries to boil down to the essence of a problem seen
when trying to use SafariViewController. The net result is DO NOT present
the SafariViewController when a popup is present.
This controller and the associated popup show 3 ways to
present the SafariViewController:
Always Good: This uses a button on the controller to simply call the
showSVC() routine and never had a problem.
Good: This is a work-around for the "Bad" case to follow. In this case,
we are using a button in a popup to bring up the SafariViewController.
The trick is to get rid of the popup before calling showSVC(). This is
done by dismissing the popup immediately without animation and then
adding a delay before calling showSVC(). Seems to work fine, but using
delays to accomplish things always seems a bit suspect. Use at your own risk.
Bad: When this goes bad, a blank white screen is presented with no way
to escape. Using "Reset Content and Settings..." in the simulator can
get one back to where it will work one time. It seemed originally that
this worked on iOS9 but not on iOS10. But now seems to fail similarly
on both iOS9 and iOS10. This case is dismissing the popup with animation
while trying to bring up the SafariViewController.
Other info: This view controller is embedded in a navigation controller -
basically to provide a navigation bar and button to act as the anchor
point for the popup. The popup provides two buttons that call back
to this controller with the "PopButtonPressedProtocol". This controller
uses the title in the popup's buttons to differentiate the "good" and
"bad" cases.
The problems shown by this example sounded similar to problems various
others reported, but these reports may be for other reasons, which may
or may not be similar.
*/
import UIKit
import SafariServices
class ViewController: UIViewController, UIPopoverPresentationControllerDelegate, PopButtonPressedProtocol {
#IBOutlet weak var btnAlwaysGood: UIButton!
#IBOutlet weak var btnPopup: UIBarButtonItem!
let webAddr = "http://www.google.com"
func delay(_ delay: Double, closure:#escaping ()->()) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
func showSVC() {
let svc = SFSafariViewController(url: URL(string: webAddr)!)
self.present(svc, animated: true, completion: nil)
}
func popButtonPressed(_ button: UIButton) {
if let title = button.currentTitle {
switch title {
case "Bad":
dismiss(animated: true, completion: nil)
showSVC()
case "Good":
dismiss(animated: false, completion: nil)
delay(0.5, closure: { self.showSVC() })
default:
break
}
}
}
func popupButtonPressed() {
performSegue(withIdentifier: "popup", sender: nil)
}
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { // Needed for popup
return .none
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
btnAlwaysGood.addTarget(self, action: #selector(showSVC), for: .touchUpInside)
btnPopup.target = self
btnPopup.action = #selector(popupButtonPressed)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? PopVC {
vc.delegate = self
vc.modalPresentationStyle = .popover
vc.preferredContentSize = CGSize(width: 60, height: 100)
if let popover = vc.popoverPresentationController {
popover.permittedArrowDirections = .any
popover.delegate = self
popover.barButtonItem = navigationItem.rightBarButtonItem
}
}
}
}
PopVC.swift:
import UIKit
protocol PopButtonPressedProtocol : class {
func popButtonPressed(_ button: UIButton) // protocol:
}
class PopVC: UIViewController {
#IBOutlet weak var btnBad: UIButton!
#IBOutlet weak var btnGood: UIButton!
weak var delegate : PopButtonPressedProtocol?
func buttonPressed(_ button: UIButton) {
delegate?.popButtonPressed(button)
}
override func viewDidLoad() {
super.viewDidLoad()
btnBad.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)
btnGood.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)
}
}
Swift 5.2, Xcode 11.4
I had similar problem, what I was doing is I was presenting UIAlertViewController and on action of its button I was present SFSafariController....this code worked perfectly on iOS 13 but iOS 12 gave problem.... apparently I had to dismiss the UIAlertViewController first before presenting SFSafariController. Hope this helps.
or else quick fix would be to use UIApplication.shared.openURL()

How to code customized pickers in a class of UIView?

I’d like to code a view (popup – window) including two picker on it in order to enter weeks (of Year) and years with two separate picker views. Firstly, I started by creating a new class as subclass of UIView. Next up, I coded the windows, which should pop up, in case it is called.
Now I’ve the problem, that I can’t fill my two picker views with data, as UIView does not support UIPickerViewDataSource.
How can I solve that problem, as I only want to show it as a small pop up and not open an entire UIViewController.
It's supposed to be a controller, displayed in a popover.
The presenter should be UIPopoverPresentationControllerDelegate with overridden method to support popovers on iPhone (by default, they are gonna be presented modally).
extension ItemViewController: UIPopoverPresentationControllerDelegate {
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return .None
}
}
Use this method to present your picker controller:
func instantiatePicker(picker: UIViewController, sender: UIView) {
picker.modalPresentationStyle = .Popover
let ppc = picker.popoverPresentationController!
ppc.delegate = self
ppc.permittedArrowDirections = .Any
ppc.sourceView = sender
ppc.sourceRect = sender.bounds
presentViewController(picker, animated: true, completion: nil)
}
In your picker controller override this property to adjust popover size to your desire, like that:
override var preferredContentSize: CGSize {
get {
return CGSize(width: datePicker.bounds.width, height: datePicker.bounds.height + anotherPicker.bounds.height)
}
set {
super.preferredContentSize = newValue
}
}

Swift - UIPopoverController in iOS 8

I'm trying to add a simple popoverController to my iphone app, and I'm currently struggling with the classic "blank screen" which covers everything when I tap the button.
My code looks like this:
#IBAction func sendTapped(sender: UIBarButtonItem) {
var popView = PopViewController(nibName: "PopView", bundle: nil)
var popController = UIPopoverController(contentViewController: popView)
popController.popoverContentSize = CGSize(width: 3, height: 3)
popController.presentPopoverFromBarButtonItem(sendTappedOutl, permittedArrowDirections: UIPopoverArrowDirection.Up, animated: true)
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController!) -> UIModalPresentationStyle {
// Return no adaptive presentation style, use default presentation behaviour
return .None
}
}
The adaptivePresentationStyleForPresentationController-function was just something I added because I read somewhere that this is what you need to implement to get this function on the iphone. But still: there is still a blank image covering the whole screen, and I do not know how to fix it.
Any suggestions would be appreciated.
The solution I implemented for this is based on an example presented in the 2014 WWDC session View Controller Advancements in iOS 8 (see the slide notes). Note that you do have to implement the adaptivePresentationStyleForPresentationController function as a part of the UIPopoverPresentationControllerDelegate, but that function should be outside of your sendTapped function in your main view controller, and you must specify UIPopoverPresentationControllerDelegate in your class declaration line in that file to make sure that your code modifies that behaviour. I also took the liberty to separate out the logic to present a view controller in a popover into its own function and added a check to make sure the function does not present the request view controller if it is already presented in the current context.
So, your solution could look something like this:
// ViewController must implement UIPopoverPresentationControllerDelegate
class TheViewController: UIViewController, UIPopoverPresentationControllerDelegate {
// ...
// The contents of TheViewController class
// ...
#IBAction func sendTapped(sender: UIBarButtonItem) {
let popView = PopViewController(nibName: "PopView", bundle: nil)
self.presentViewControllerAsPopover(popView, barButtonItem: sender)
}
func presentViewControllerAsPopover(viewController: UIViewController, barButtonItem: UIBarButtonItem) {
if let presentedVC = self.presentedViewController {
if presentedVC.nibName == viewController.nibName {
// The view is already being presented
return
}
}
// Specify presentation style first (makes the popoverPresentationController property available)
viewController.modalPresentationStyle = .Popover
let viewPresentationController = viewController.popoverPresentationController?
if let presentationController = viewPresentationController {
presentationController.delegate = self
presentationController.barButtonItem = barButtonItem
presentationController.permittedArrowDirections = .Up
}
viewController.preferredContentSize = CGSize(width: 30, height: 30)
self.presentViewController(viewController, animated: true, completion: nil)
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return .None
}
}
Real world implementation
I implemented this approach for input validation on a sign up form in an in-progress app that I host on Github. I implemented it as extensions to UIVIewController in UIViewController+Extensions.swift. You can see it in use in the validation functions in AuthViewController.swift. The presentAlertPopover method takes a string and uses it to set the value of a UILabel in a GenericAlertViewController that I have set up (makes it easy to have dynamic text popovers). But the actual popover magic all happens in the presentViewControllerAsPopover method, which takes two parameters: the UIViewController instance to be presented, and a UIView object to use as the anchor from which to present the popover. The arrow direction is hardcoded as UIPopoverArrowDirection.Up, but that wouldn’t be hard to change.

Resources