SWRevealViewController toggle not working with custom Navigation Bar Button - ios

I am using SWRevealViewController to show a side menu in Swift 2.0 I have downloaded the files from GitHub, created the bridging header and connected segues correctly. I am creating a custom button but the action "reveal toggle" is not firing. Where am I making a mistake?
super.viewDidLoad()
self.navigationController?.navigationBar.topItem?.title = "DASHBOARD"
self.navigationController!.navigationBar.tintColor = UIColor.whiteColor()
self.navigationController!.navigationBar.titleTextAttributes =
[NSForegroundColorAttributeName: UIColor.whiteColor()]
self.navigationController!.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "Teko-Regular", size: 26)!]
self.navigationController?.navigationBar.barTintColor = UIColor.redColor()
let btnName = UIButton()
btnName.setImage(UIImage(named: "LeftNavItem"), forState: .Normal)
btnName.frame = CGRectMake(0, 0, 20, 20)
let leftBarButton = UIBarButtonItem()
leftBarButton.customView = btnName
self.navigationItem.leftBarButtonItem = leftBarButton
if self.revealViewController() != nil {
//print(self.revealViewController())
leftBarButton.target = self.revealViewController()
leftBarButton.action = Selector("revealToggle:")
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
The gesture recognizer is firing properly, but not the "revealToggle:" What's the mistake?

class Name: SWRevealViewControllerDelegate
override func viewDidLoad() {
super.viewDidLoad()
self.revealViewController().delegate = self
}

I was facing same issues using SWRevealViewController.
Solution :**After Login i was calling dashboard screen before But now
i replaced with SWrevealviewcontroller like below code.that's it now working fine
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController1 =
storyboard.instantiateViewController(withIdentifier: "SWRevealViewController") as! SWRevealViewController
self.present(viewController1, animated: true,completion: nil)
*Add below code in viewdidload() method
if revealViewController() != nil {
menuoutlet.target = self.revealViewController()
menuoutlet.action = #selector(SWRevealViewController.revealToggle(_:))
self.view.addGestureRecognizer(revealViewController().panGestureRecognizer())
self.revealViewController().rearViewRevealWidth = 240
}
Menu button action code
#IBAction func menu(_ sender: Any) {
let btntitle = (sender as AnyObject).currentTitle!
self.revealViewController().rearViewController.performSegue(withIdentifier: btntitle!, sender: self.revealViewController().rearViewController)
}

Related

NavigationBar can't display title

I create a UINavigationController object, but it can't set the title.
class LogInSwitchingViewController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.white
self.navigationItem.title = "This is title"
self.navigationBar.tintColor = UIColor.black
let vc1 = UIViewController()
vc1.view.backgroundColor = UIColor.brown
self.pushViewController(vc1, animated: true)
}
You need to update the title property of the visible view controller, not the navigation controller itself:
let vc1 = UIViewController()
vc1.title = "This is title"
vc1.view.backgroundColor = UIColor.brown
self.pushViewController(vc1, animated: true)

CNContactViewController navigation bar colour not working properly

CNContactViewController navigation bar colour not appearing when i click Create New Contact option. See my screens for 1st time it's ok, but when i click Create New Contact i'm not getting navigation bar colour and not visible back button.
1st screen
2nd screen
In older versions
My code is
if #available(iOS 9.0, *) {
let store = CNContactStore()
let contact = CNMutableContact()
let homePhone = CNLabeledValue(label: CNLabelHome, value: CNPhoneNumber(stringValue : self.mobile ?? ""))
contact.phoneNumbers = [homePhone]
let controller = CNContactViewController(forUnknownContact : contact)
controller.contactStore = store
controller.delegate = self
if #available(iOS 10.0, *) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: {
//Set status bar background colour
let statusBar = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView
statusBar?.backgroundColor = UIColor.red
//Set navigation bar subView background colour
for view in controller.navigationController?.navigationBar.subviews ?? [] {
view.tintColor = UIColor.white
view.backgroundColor = UIColor.red
}
})
}
navigationController?.pushViewController(controller, animated: true)
}
And one more is by default phone number: (913) 351-5518
I would suggest to display a CNConctactViewController within a UINavigationController in Popover Modal Presentation style, and add a few button to return to the main application. This implementation seams not trivial as reported by rumours over the net.
Let me share a few pieces of my code (swift 5).
The major class:
class MyViewController: UITableViewController, UIPopoverPresentationControllerDelegate {
var contactViewController = CNContactViewController()
...
#objc func dismissContactViewController() {
contactViewController.dismiss(animated: true, completion: nil)
}
}
The extension:
extension MyViewController: CNContactViewControllerDelegate {
func openCNContactViewController(willAppearWith: CNContact, type: ContactType) {
switch type {
case .forContact:
contactViewController = CNContactViewController(for: willAppearWith)
contactViewController.allowsEditing = false
break
case .forNewContact:
contactViewController = CNContactViewController(forNewContact: willAppearWith)
contactViewController.allowsEditing = true
break
case .forUnknowContact:
contactViewController = CNContactViewController(forUnknownContact: willAppearWith)
contactViewController.allowsEditing = true
break
}
contactViewController.allowsActions = true
contactViewController.contactStore = globalContactStore
contactViewController.hidesBottomBarWhenPushed = true
contactViewController.delegate = self
// define the button (or select a default one)
let button = UIButton(type: .custom)
button.setTitleColor(self.view.tintColor, for: .normal)
button.setTitle("My app name", for: .normal)
button.addTarget(self, action: #selector(dismissContactViewController), for: .touchUpInside)
let closeButton = UIBarButtonItem(customView: button)
closeButton.style = .plain
// add flexible space
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
// add to toolbar
contactViewController.setToolbarItems([flexibleSpace, closeButton, flexibleSpace], animated: false)
let navigationVC = UINavigationController(rootViewController: contactViewController)
// show toolbar
navigationVC.setToolbarHidden(false, animated: false)
// set navigation presentation style
navigationVC.modalPresentationStyle = .popover
// present view controller
self.present(navigationVC, animated: true, completion: nil)
}
The result

How to make a transparent background of Popup ViewController?

I've a ViewController as popup to pick a date on UIDatePicker. But when, this popup opens, the background is covered by new background color. I tried choose a opacity of color, but this not works.
I use a UILabel to handler click and open a new ViewController.
override func viewDidLoad() {
super.viewDidLoad()
let tapDateSelectExpiration = UITapGestureRecognizer(target: self, action: #selector(handleSelectDateExpiration))
let tapDateSelectValidity = UITapGestureRecognizer(target: self, action: #selector(handleSelectDateValidity))
let tapDateSelectOrder = UITapGestureRecognizer(target: self, action: #selector(handleSelectDateOrder))
lblDataPedido.isUserInteractionEnabled = true
lblDataValidade.isUserInteractionEnabled = true
lblDataExpiracao.isUserInteractionEnabled = true
lblDataPedido.addGestureRecognizer(tapDateSelectOrder)
lblDataValidade.addGestureRecognizer(tapDateSelectValidity)
lblDataExpiracao.addGestureRecognizer(tapDateSelectExpiration)
}
#objc func handleSelectDateExpiration(_ sender : UILabel) {
print("handleSelectDateExpiration")
var vcSelectDate = self.storyboard?.instantiateViewController(withIdentifier: "ViewControllerSelectDate") as! ViewControllerSelectDate
vcSelectDate.typeDate = "DateExpiration"
self.present(vcSelectDate,animated: true,completion: nil)
}
// Other funcs as above.
MainLayout:
DatePicker layout with backgroud not transparent:
Storyboard:
You can try
let vc = self.storyboard?.instantiateViewController(withIdentifier: "dateView") as! dateViewController
vc.delegate = self
vc.providesPresentationContextTransitionStyle = true;
vc.definesPresentationContext = true;
vc.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
self.present(vc, animated: false, completion: nil)
and select transparent background like this
or in IB

Tab Bar Item won't show

Currently I have 1 tab view controller, with 3 menus:
But when running, the bottom menu / image are like being cutted or didn't show perfectly like this:
It should have 3 menus.
Code:
import UIKit
class TabBarReimbursementViewController: UITabBarController{
var loadTable: Bool = false
override func viewWillAppear(animated: Bool) {
self.viewControllers![selectedIndex].viewWillAppear(true)
}
override func viewDidLoad() {
super.viewDidLoad()
// self.tabBar.barTintColor = UIColor.redColor()
self.tabBar.tintColor = UIColor.blackColor()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(TabBarReimbursementViewController.buttonClicked(_:)))
navigationItem.rightBarButtonItem = addButton
// UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor() ], forState: .Normal)
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.blackColor() ], forState: .Selected)
let historySelected: UIImage! = UIImage(named: "history2.png")?.imageWithRenderingMode(.AlwaysOriginal)
let approvalSelected: UIImage! = UIImage(named: "approve2.png")?.imageWithRenderingMode(.AlwaysOriginal)
let listSelected: UIImage! = UIImage(named: "listlist2.png")?.imageWithRenderingMode(.AlwaysOriginal)
(tabBar.items![1] ).selectedImage = historySelected
(tabBar.items![0] ).selectedImage = approvalSelected
(tabBar.items![2] ).selectedImage = listSelected
self.selectedViewController = self.viewControllers![1]
self.findHamburguerViewController()?.gestureEnabled = false
}
func buttonClicked(sender: UIBarButtonItem) {
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("MyRequestForm") as! myRequestForm
nextViewController.formType = "New"
self.navigationController!.pushViewController(nextViewController, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You CAPSPageMenu Library in which you can use tab bar controller very easily CAPSPageMenu
just add below code in Library
_menuScrollView.translatesAutoresizingMaskIntoConstraints = NO;
_menuScrollView.frame = CGRectMake(0.0, self.view.frame.size.width- _menuHeight,self.view.frame.size.width, _menuHeight);
The thing is that what you are doing is not how a tab bar controller's tab bar items work. Each child view controller (there are three of them in your storyboard screen shot) has its own tabBarItem, and that is how the tab bar gets populated.

Swift Custom Back Button and Destination

I am currently using SWRevealViewController for a sidebar menu in my app. When I click one of the options, the destination view controller doesn't have a 'back' button because it hasn't come from a proper view controller (i.e. page to go back to).
Therefore I am wanting to manually create a back button on the destination view controller which will go back to the home view controller.
I have looked at the code here: How do I manually set the "Back" destination in iOS apps
But I am struggling to implement this in Swift (one error after another!). Any help? Thanks!
EDIT
I have tried the suggestion below, but the back button just doesn't appear. This may have something to with the fact I have the navbar hidden in other views and do the following on the destination view:
override func viewDidLoad() {
super.viewDidLoad()
navigationController.setNavigationBarHidden(false, animated:true)
var myBackButton:UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
myBackButton.addTarget(self, action: "popToRoot:", forControlEvents: UIControlEvents.TouchUpInside)
var myCustomBackButtonItem:UIBarButtonItem = UIBarButtonItem(customView: myBackButton)
self.navigationItem.leftBarButtonItem = myCustomBackButtonItem
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func popToRoot(sender:UIBarButtonItem){
self.navigationController.popToRootViewControllerAnimated(true)
}
Not sure why the back button won't show up?
Edit
This is the prepareForSegue from my sidebar view controller. If there is a way to check for the segue identifier 'test' then I can set the back button from here?
- (void) prepareForSegue: (UIStoryboardSegue *) segue sender: (id) sender
{
// Set the title of navigation bar by using the menu items
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
UINavigationController *destViewController = (UINavigationController*)segue.destinationViewController;
destViewController.title = [[_menuItems objectAtIndex:indexPath.row] capitalizedString];
if ( [segue isKindOfClass: [SWRevealViewControllerSegue class]] ) {
SWRevealViewControllerSegue *swSegue = (SWRevealViewControllerSegue*) segue;
swSegue.performBlock = ^(SWRevealViewControllerSegue* rvc_segue, UIViewController* svc, UIViewController* dvc) {
UINavigationController* navController = (UINavigationController*)self.revealViewController.frontViewController;
[navController setViewControllers: #[dvc] animated: NO ];
[self.revealViewController setFrontViewPosition: FrontViewPositionLeft animated: YES];
};
}
}
You can write that in swift like this
Write this to add button on navigationController
navigationController.setNavigationBarHidden(false, animated:true)
var myBackButton:UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
myBackButton.addTarget(self, action: "popToRoot:", forControlEvents: UIControlEvents.TouchUpInside)
myBackButton.setTitle("YOUR TITLE", forState: UIControlState.Normal)
myBackButton.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
myBackButton.sizeToFit()
var myCustomBackButtonItem:UIBarButtonItem = UIBarButtonItem(customView: myBackButton)
self.navigationItem.leftBarButtonItem = myCustomBackButtonItem
this will pops to rootViewController
func popToRoot(sender:UIBarButtonItem){
self.navigationController.popToRootViewControllerAnimated(true)
}
Swift 3.0 Solution:
self.navigationController?.setNavigationBarHidden(false, animated:false)
//Create back button of type custom
let myBackButton:UIButton = UIButton.init(type: .custom)
myBackButton.addTarget(self, action: #selector(ViewController.popToRoot(sender:)), for: .touchUpInside)
myBackButton.setTitle("Back".localized(), for: .normal)
myBackButton.setTitleColor(.blue, for: .normal)
myBackButton.sizeToFit()
//Add back button to navigationBar as left Button
let myCustomBackButtonItem:UIBarButtonItem = UIBarButtonItem(customView: myBackButton)
self.navigationItem.leftBarButtonItem = myCustomBackButtonItem
func popToRoot(sender:UIBarButtonItem){
_ = self.navigationController?.popToRootViewController(animated: true)
}
In Swift 2.1
I am customizing Navigation Bar Items this way
I can change Navigation bar background image, title text, text color
I can show/hide back button
I can Change Title/ Icon or custom action method
In AppDelegate I have
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
//Cutomize navigation bar
let navBgImage:UIImage = UIImage(named: "dummy_navigation_bg_image")!
UINavigationBar.appearance().setBackgroundImage(navBgImage, forBarMetrics: .Default)
UINavigationBar.appearance().tintColor = UIColor.whiteColor()
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()];
return true
}
In ViewController I update Navigation Items in viewWillAppear method this way
override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated)
setupNavigationBar()
}
// MARK: - NavigationBar methods
func setupNavigationBar ()
{
//current tab screen title
tabBarController?.title = "Manage"
//Hide back button or left bar button
tabBarController?.navigationItem.leftBarButtonItem = UIBarButtonItem(title: " ", style: .Plain, target: nil, action: nil)
//custom right bar button
var image = UIImage(named: "dummy_settings_icon")
image = image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
tabBarController?.navigationItem.rightBarButtonItem = UIBarButtonItem(image: image, style: UIBarButtonItemStyle.Plain, target: self, action: "settingButtonAction")
}
func settingButtonAction()
{
print("Setting Button tapped")
performSegueWithIdentifier("loadAccountSettingsSegue", sender: nil)
}
Here's an updated version for Swift 2/2.1:
self.navigationController? .setNavigationBarHidden(false, animated:true)
let backButton = UIButton(type: UIButtonType.Custom)
backButton.addTarget(self, action: "methodCall:", forControlEvents: UIControlEvents.TouchUpInside)
backButton.setTitle("TITLE", forState: UIControlState.Normal)
backButton.sizeToFit()
let backButtonItem = UIBarButtonItem(customView: backButton)
self.navigationItem.leftBarButtonItem = backButtonItem
Swfit 5 / XCode 11.4
override func viewDidLoad() {
super.viewDidLoad()
navigationController!.setNavigationBarHidden(false, animated: true)
let myBackButton:UIButton = UIButton(type: UIButton.ButtonType.custom) as UIButton
myBackButton.addTarget(self, action: #selector(popToRoot), for: UIControl.Event.touchUpInside)
myBackButton.setTitle("YOUR TITLE", for: UIControl.State.normal)
myBackButton.setTitleColor(UIColor.white, for: UIControl.State.normal)
myBackButton.sizeToFit()
let myCustomBackButtonItem:UIBarButtonItem = UIBarButtonItem(customView: myBackButton)
self.navigationItem.leftBarButtonItem = myCustomBackButtonItem
}
Also, popToRoot you should mark as #objc
#objc func popToRoot() {
//enter action here
}

Resources