Creating a custom back button across my app - ios

I’m trying to change the default look of Navigation Controller back button across my app.
I would like to use and image(icon) and remove the “Back” text.
This code stretched the image across the button and does not remove the button title.
let backImg: UIImage = UIImage(named: "icon_back")!
UIBarButtonItem.appearance().setBackButtonBackgroundImage(backImg, for: .normal, barMetrics: .default)
An recommendation how to do is inside AppDelegate (didFinishLaunchingWithOptions)?

The easy way of doing is just create one BaseViewController for your project which is derived from UIViewController. You can have on common method in BaseViewController to create your custom leftBarButton in every viewController. The remaining viewController in your project should be derived from this BaseViewController,
class BaseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
createLeftBarButton(image: #Pass image here#, width: #Pass width of your image view#) // Create custom back bar button.
}
/**Create cutom back bar button*/
func createLeftBarButton(image: UIImage?, width: CGFloat) {
let backButton: UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: width, height: 50))
backButton.imageView?.contentMode = .scaleAspectFill
backButton.imageView?.bounds = CGRect(x: 0, y: 0, width: width, height: width)
backButton.setImage(image, for: .normal)
backButton.setImage(image, for: .highlighted)
backButton.addTarget(self, action: #selector(leftBarButtonItemPressed(_:)), for: .touchUpInside)
let leftItem: UIBarButtonItem = UIBarButtonItem(customView: backButton)
navigationItem.leftBarButtonItem = leftItem
}
/**Custom back bar button pressed. So handle here*/
func leftBarButtonItemPressed(_ sender: UIButton) {
view.endEditing(true) // End editing if any.
if isViewControllerPresented() { // Check view controller is presented or pushed
dismiss(animated: true, completion: nil) // Dismiss ViewController if presented
} else {
_ = navigationController?.popViewController(animated: true) // Pop ViewController if pushed
}
}
/**To check whether view controller is presented or pushed.*/
func isViewControllerPresented() -> Bool {
if self.presentingViewController?.presentedViewController == self {
return true
}
if (self.navigationController != nil && self.navigationController?.presentingViewController?.presentedViewController == self.navigationController) && self.navigationController?.viewControllers.count == 1 {
return true
}
if self.tabBarController?.presentingViewController is UITabBarController {
return true
}
return false
}
}
// Sub class your remaining viewControllers like this.
class FirstViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad() // When calling this super method, the custom back bar button will be created for you
}
}
Thanks.

You can doing this by setting the navigationItem's BackButtonBackgroundImage;
also you can set the appearance for global effect:
let item = UIBarButtonItem.appearance(whenContainedInInstancesOf: [UINavigationBar.self])
item.setBackButtonBackgroundVerticalPositionAdjustment(-10, for: .default) item.setBackButtonBackgroundImage(youImage, for: .normal, barMetrics: .default)
for removing the back title, you can do like this:
#implementation UINavigationItem (BackItem)
-(UIBarButtonItem *)backBarButtonItem {
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:#" " style:UIBarButtonItemStylePlain target:nil action:nil];
item.tintColor = [UIColor darkGrayColor];
return item;
}
#end

Related

How to adjust sublayer on UINavigationController?

In my Swift project, I added a sublayer to UINavigationController.
But after adding this GAGradientLayer, I can't see the navigation title text or back button.
The weird thing is that in the view hierarchy, the CAGradientLayer(which was added as sublayer) is behind the title and button.
I tried to reload navigationController layer with LayoutIfNeeded, setNeedsLayout or setNeedsDisplay but nothing worked.
And I also just tried to change the navigation title but it doesn't work.
(Actually The text of navigation title is loaded on the view controller behind, so I don't want to change this on this VC.)
So, How can I show my navigation title text and button with CAGradientlayer above?
Here's the screenshot
Here's the codes needed
import UIKit
import SnapKit
class BulletinBoardViewController: UIViewController {
// ...
var backgroundGradientLayer: CAGradientLayer?
let bulletinBoardView = BulletinBoardView()
// MARK: - Lifecycles
override func viewDidLoad() {
super.viewDidLoad()
setBulletinBoardView()
setCells()
}
override func viewWillAppear(_ animated: Bool) {
setupBackgroundLayer()
}
override func viewWillDisappear(_ animated: Bool) {
self.backgroundGradientLayer?.removeFromSuperlayer()
}
// MARK: - Helpers
func setupBackgroundLayer() {
DispatchQueue.main.async {
if let backgroundGradientLayer = self.backgroundGradientLayer {
backgroundGradientLayer.frame = CGRect(x: 0, y: -59, width: 500, height: 103)
self.navigationController?.navigationBar.layer.addSublayer(backgroundGradientLayer)
}
}
}
func setBulletinBoardView() {
self.view.addSubview(bulletinBoardView)
bulletinBoardView.snp.makeConstraints { make in
make.right.left.top.equalTo(self.view.safeAreaLayoutGuide)
make.bottom.equalTo(self.view)
}
}
// ...
}
The origin navigation controller setting is below
class MainPageViewController: UIViewController {
// ...
func setupNav() {
navigationController?.navigationBar.tintColor = .black
navigationItem.rightBarButtonItem = listButton
navigationItem.leftBarButtonItem = settingButton
let backBarButtonItem = UIBarButtonItem(title: "",
style: .plain,
target: self,
action: nil)
self.navigationItem.backBarButtonItem = backBarButtonItem
let appearance = UINavigationBarAppearance()
appearance.configureWithOpaqueBackground()
appearance.backgroundColor = .systemGray3
appearance.titleTextAttributes = [NSAttributedString.Key.font: UIFont(name: AppFontName.bold, size: 20)!]
navigationController?.navigationBar.standardAppearance = appearance
navigationController?.navigationBar.scrollEdgeAppearance =
navigationController?.navigationBar.standardAppearance
}
// ...
}

custom back button in navigation in iOS

I know this question has been asked before but nothing worked for me and I had to ask it again.
I want an image as my back button in navigation bar, just want to change the appearance of the back button. I don't want to add a button and add selectors for it.
I tried the following code:
let backImage = UIImage(named: "Back_button")
let backAppearance = UIBarButtonItem.appearance()
backAppearance.setBackButtonBackgroundImage(backImage, for: .normal, barMetrics: .default)
navigationController?.navigationBar.backIndicatorTransitionMaskImage = backImage
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItem.Style.plain, target: nil, action: nil)
I also tried setting the back image and back mask using storyboard but both these approaches place a black circle on my back image.
I tried setting another image as back mask by setting its alpha content equal to zero using the code but it didn't work either.
please help.
let backButton = UIBarButtonItem()
backButton.title = "Back"
backButton.image = UIImage(named: "Back_button")
self.navigationController?.navigationBar.topItem?.backBarButtonItem = backButton
You can do this to customize your Back button. And you don't have to worry about adding selectors.
This code works with Swift 5.
let backButton: UIButton = UIButton()
backButton.setImage(UIImage(named: "back"), for: UIControl.State())
backButton.addTarget(self, action:#selector(SearchResultsViewController.onBack), for: UIControl.Event.touchUpInside)
let leftBarButtonItem = UIBarButtonItem(customView: backButton)
navigationItem.leftBarButtonItem = leftBarButtonItem
I used this code to customize the back button on only one of my views:
self.navigationController?.navigationBar.topItem?.backButtonTitle = ""
let backButton = UIBarButtonItem(image: UIImage(named: "back"), style: .plain, target: self, action: #selector(goBack))
navigationItem.leftBarButtonItem = backButton
#objc func goBack() {
self.navigationController?.popViewController(animated: true)
}
Create a custom class for define navigation bar traits
Create an extension to UINavigationController for configure it
import UIKit
private final class MyNavigationBarTraits {
public var backIndicatorImage: UIImage?
public var backIndicatorTransitionMaskImage: UIImage?
public func apply(to navigationBar: UINavigationBar) {
navigationBar.backIndicatorImage = backIndicatorImage
navigationBar.backIndicatorTransitionMaskImage = backIndicatorTransitionMaskImage
}
public init(navigationBar: UINavigationBar) {
backIndicatorImage = navigationBar.backIndicatorImage
backIndicatorTransitionMaskImage = navigationBar.backIndicatorTransitionMaskImage
}
}
public typealias Callback<T> = (_: T) -> Void
public extension UINavigationController {
private struct AssociationKeys {
static var navigationBarTraits = "ws_nc_navigationBarTraits"
}
private var navigationBarTraits: MyNavigationBarTraits? {
get {
return objc_getAssociatedObject(self, &AssociationKeys.navigationBarTraits) as? MyNavigationBarTraits
}
set {
objc_setAssociatedObject(self, &AssociationKeys.navigationBarTraits, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
func configureBar(block: Callback<UINavigationBar>) {
navigationBarTraits = MyNavigationBarTraits(navigationBar: navigationBar)
block(navigationBar)
}
func resetBar() {
navigationBarTraits?.apply(to: navigationBar)
navigationBarTraits = .none
}
}
And then you can configure your navigation bar in your ViewController's viewWillAppear (for example tintColor)
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.configureBar { navigationBar in
// You can customize your navigation bar in here!
navigationBar.tintColor = .red
}
}
If you want to use this customization just in one View Controller you should reset bar in your View Controller's viewWillDisappear
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.resetBar()
}
Simply Add Below Methods in Your ViewController :
func setLeftBarBackItem() {
let leftBarBackItem = UIBarButtonItem(image: #imageLiteral(resourceName: "imgBack"), style: .plain, target: self, action: #selector(self.clickToBtnBackItem(_:)))
self.navigationItem.leftBarButtonItem = leftBarBackItem
}
func clickToBtnBackItem(_ sender: UIBarButtonItem) {
view.endEditing(true)
_ = navigationController?.popViewController(animated: true)
}
func setTranspertNavigation()
{
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.view.backgroundColor = .clear
}
Inside Your ViewController's ViewDidLoad Method, Set backButton As :
self.navigationController?.isNavigationBarHidden = false
AppDelegate.shared().setupNavigationBar()
setLeftBarBackItem()
setTranspertNavigation()
self.title = "Title Here"

Create a button programatically in differrent class swift

I am new to swift and trying to create a UIButton programmatically. I have two classes. I am creating a button in one class and calling that method from another class.
class viewcontroller
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let renderobj = render()
renderobj.sign()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
class render
import UIKit
class render: UIViewController {
func sign() {
let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
button.backgroundColor = .green
button.setTitle("Test Button", for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
self.view.addSubview(button)
}
func buttonAction(sender: UIButton!) {
print("Button tapped")
}
}
But no button is created. If I put the UIButton code inside viewDidLoad() , it works. I want the button to be created in a function of different class. Is it possible to do so ?
Thanks for any help
func sign() -> UIButton
{
let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
button.backgroundColor = .green
button.setTitle("Test Button", for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
return button
}
After returning that button you can add it in your calling view controller view
override func viewDidLoad() {
super.viewDidLoad()
let renderobj = render()
let button = renderobj.sign()
self.view.addSubview(button)
}
After doing this
let renderobj = render()
And after calling this function, a new button is initialized and added to the view of render view controller.
renderobj.sign()
But renver view controller is only initialized and its view is not added to current view controller which is ViewController
If you want to show render controller, then present it like usual. If you want to add that button to your ViewController then either declare a button variable and access it or return it in sign() function
I think there is a lack of understanding around the concepts of a UIViewController here. A UIViewController is used to manage the views displayed to a user, think about it as a single screen of your app. You can embed view controllers in other view controllers, but typically you won't need to do this for basic stuff.
A UIViewController has a lifecycle which you can find more about here: https://developer.apple.com/reference/uikit/uiviewcontroller#1652793
Now what it appears like you want to do is to wrap up the functionality of creating a button, you can do this by either creating a factory method in you ViewController class (or other class somewhere else), or by subclassing UIButton and creating a convenience initialiser method to create the button with the properties you want (you can also use Swift extensions but I won't go into that here).
Lets look at the simplest method and create a factory method inside your ViewController class:
// The button method takes a title and a selector (the selector is the method that should be called when the button is tapped)
func makeButton(title: String, action: Selector) -> UIButton {
// Create a basic button with a default size
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
// Customise the button with your settings
button.backgroundColor = .green
button.setTitle(title, for: .normal)
button.addTarget(self, action: action, for: .touchUpInside)
// Return the newly created button
return button
}
Now we have a method that creates a button of a default size and position, we want to call that method to create a button and then add it as a subview of the ViewController's view. To do that we can do something in the viewDidLoad() method that we override:
override func viewDidLoad() {
// Always remember to call the super method to ensure all super classes have a chance to do any work thats required by them
super.viewDidLoad()
// Create the button by calling our new method
let button = self.makeButton(title: "Test Button", action: #selector(buttonTapped))
// Set the origin of the button to move it to the right position
button.frame.origin = CGPoint(x: 100, y: 100)
// Finally add the new button as a subclass of the view controllers view
self.view.addSubview(button)
}
Now we understand whats going on in the methods we can put it all together to have a class that looks like this:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = self.makeButton(title: "Test Button", action: #selector(buttonTapped))
button.frame.origin = CGPoint(x: 100, y: 100)
self.view.addSubview(button)
}
func makeButton(title: String, action: Selector) -> UIButton {
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
button.backgroundColor = .green
button.setTitle(title, for: .normal)
button.addTarget(self, action: action, for: .touchUpInside)
return button
}
func buttonTapped(sender: UIButton) {
print("Button tapped")
}
}
You create new UIViewController here:
let renderobj = render()
renderobj.sign()
but ViewController instance is showing in this moment.

How to add buttons above keyboard

How to add button above the keyboard like this one in Stack Exchange app? And when you long press the text in UITextView How to add "Select" and "Select All"?
The first question, you can set textField's inputAccessoryView to your custom view, this can customize the keyboard's header.
The result:
You can do it like below;
first, you should instance the view you want to add above the keyboard.
class ViewController : UIViewController {
#IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textField.inputAccessoryView = Bundle.main.loadNibNamed("CustomAccessoryView", owner: self, options: nil)?.first as! UIView?
In your CustomAccessoryView, you can set the action of the button:
import UIKit
class CustomAccessoryView: UIView {
#IBAction func clickLoveButton(_ sender: UIButton) {
print("Love button clicked")
}
}
I would recommend to create a toolbar for your UITextField's accessoryView property.
The idea is to add this toolbar once, before the textfield would show for the first time. Therefore, we assign the delegate to self, and override the textFieldShouldBeginEditing delegate call with our implementation to add the accessoryView.
Here is a simple example, how can u achieve it:
import UIKit
class ViewController: UIViewController {
// your `UITextfield` instance
// Don't forget to attach it from the IB or create it programmaticly
#IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Assign the delegate to self
textField.delegate = self
}
}
// MARK: Create extension to conform to UITextfieldDelegate
extension ViewController: UITextFieldDelegate {
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
setupTextFieldsAccessoryView()
return true
}
func setupTextFieldsAccessoryView() {
guard textField.inputAccessoryView == nil else {
print("textfields accessory view already set up")
return
}
// Create toolBar
let toolBar: UIToolbar = UIToolbar(frame:CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 44))
toolBar.barStyle = UIBarStyle.black
toolBar.isTranslucent = false
// Add buttons as `UIBarButtonItem` to toolbar
// First add some space to the left hand side, so your button is not on the edge of the screen
let flexsibleSpace: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil) // flexible space to add left end side
// Create your first visible button
let doneButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(didPressDoneButton))
// Note, that we declared the `didPressDoneButton` to be called, when Done button has been pressed
toolBar.items = [flexsibleSpace, doneButton]
// Assing toolbar as inputAccessoryView
textField.inputAccessoryView = toolBar
}
func didPressDoneButton(button: UIButton) {
// Button has been pressed
// Process the containment of the textfield or whatever
// Hide keyboard
textField.resignFirstResponder()
}
}
This should be your output:
You'll have to use the inputAccessoryView of your textfield.
you can put the code snippet below in your viewDidLoad():
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 60))
button.backgroundColor = UIColor.blue
button.setTitle("NEXT", for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.addTarget(self, action: #selector(self. yourButton), for: .touchUpInside)
numtextField.inputAccessoryView = button
}
#objc func nextButton()
{
print("do something")
}
Just copy and paste simple code for you accessory button embedded with keypad
func addKeyboardToolbar() {
let ViewForDoneButtonOnKeyboard = UIToolbar()
ViewForDoneButtonOnKeyboard.sizeToFit()
let button = UIButton.init(type: .custom)
button.setImage(UIImage.init(named: "login-logo"), for: UIControlState.normal)
button.addTarget(self, action:#selector(doneBtnfromKeyboardClicked), for:.touchUpInside)
button.frame = CGRect.init(x: 0, y: 0, width:UIScreen.main.bounds.width, height: 30) //CGRectMake(0, 0, 30, 30)
let barButton = UIBarButtonItem.init(customView: button)
ViewForDoneButtonOnKeyboard.items = [barButton]
postTextView.inputAccessoryView = ViewForDoneButtonOnKeyboard
}
func doneBtnfromKeyboardClicked (){
self.contentView.endEditing(true)
}
to add a toolbar with a done button which dismisses the keyboard above a UITextField you can write a UITextField extension with the following function:
public func addAccessoryView() {
let doneButton = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "resignFirstResponder")
let flexSpace: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil)
let toolbar = UIToolbar()
toolbar.barStyle = UIBarStyle.Default
toolbar.translucent = true
toolbar.tintColor = Color.blue
toolbar.sizeToFit()
toolbar.setItems([flexSpace, doneButton], animated: false)
toolbar.userInteractionEnabled = true
self.inputAccessoryView = toolbar
}
you can then call the function in your textfield like this:
textfield.addAccessoryView()

Default Back Button Text and Font Setting

By default, Navigation back button text comes as previous screen title or <
I am trying to change that to just <=|
But Its coming as shown in the picture
BackButton Image.
So, I want to know how to change its font to make big <=| and remove the default <
I tried
Tried the same code in viewDidLoad of first start screen,
So i also want to know where to place this code:
override func viewWillAppear(animated: Bool)
{
self.navigationItem.leftBarButtonItem?.title = "<=|"
let FntStgVal = [NSFontAttributeName:UIFont.systemFontOfSize(50, weight: UIFontWeightLight)]
self.navigationItem.leftBarButtonItem?.setTitleTextAttributes(FntStgVal, forState: .Normal)
}
Change your code in viewDidLoad like this.
class BaseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
func setNavigationWithCustomBackButton() {
let btnLeft:UIButton! = UIButton(frame: CGRectMake(0, 0, 20, 16))
btnLeft.setTitle("<=|", forState: .Normal)
btnLeft.titleLabel?.font = UIFont.systemFontOfSize(19, weight: UIFontWeightLight)
btnLeft!.addTarget(self, action: "handleBack:",forControlEvents: UIControlEvents.TouchUpInside)
let leftItem:UIBarButtonItem = UIBarButtonItem(customView: btnLeft!)
self.navigationItem.leftBarButtonItem = leftItem
}
func handleBack(sender: UIButton) {
self.navigationController?.popViewControllerAnimated(true)
}
}
Now use this BaseViewController as parent of your all viewController and call its method in viewDidLoad like this.
class ViewController1: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.setNavigationWithCustomBackButton()
}
}
Now it will add custom back button in your NavigationBar.
Hope this will help you.

Resources