BarButtonItem EdgeInsets doesn't work - ios

I'm trying to add a padding to the right of a navigationBar rightBarButtonItems in between the buttons but it's now working.
Here's the button creation code with the given inset:
lazy var previewBarButtonItem: UIBarButtonItem = {
let buttonItem = UIBarButtonItem(title: "Preview", style: .plain, target: self, action: #selector(handlePreview))
buttonItem.tintColor = UIColor.black
buttonItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 14)], for: .normal)
buttonItem.imageInsets = UIEdgeInsetsMake(0, -15, 0, 15)
return buttonItem
}()
override func viewDidLoad() {
super.viewDidLoad()
setupRightNavItems()
}
fileprivate func setupRightNavItems () {
navigationItem.rightBarButtonItems = [submitBarButtonItem, previewBarButtonItem]
}
Can you give a hint on why this isn't working?
Thanks

I managed to fix this issue, just added a fixedSpace in-between the bar button items as follows:
1) remove any EdgeInsets
2) add the following fixed space:
fileprivate func setupRightNavItems () {
let spacing = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
spacing.width = 25 //change to your desired space width
navigationItem.rightBarButtonItems = [submitBarButtonItem, spacing, previewBarButtonItem]
}

Related

Why is the toolbar not showing when I tap on the textfield?

I would like to implement a done toolbar above the numpad keyboard when the textfield is tapped however the toolbar is not showing up for some reason.
The following code sample has been used:
extension UITextField{
#IBInspectable var doneAccessory: Bool{
get{
return self.doneAccessory
}
set (hasDone) {
if hasDone{
addDoneButtonOnKeyboard()
}
}
}
func addDoneButtonOnKeyboard()
{
let doneToolbar: UIToolbar = UIToolbar(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
doneToolbar.barStyle = .default
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.doneButtonAction))
let items = [flexSpace, done]
doneToolbar.items = items
doneToolbar.sizeToFit()
self.inputAccessoryView = doneToolbar
}
#objc func doneButtonAction()
{
self.resignFirstResponder()
}
}
Make sure in your storyboard, TextField's property inspector doneAccessory property is set to ON
and O/P looks like

iOS toolbar barbuttonitem spacer

I am trying to add two bar buttons to toolbar in iOS [Cancel] & [Save] on right and left side accordingly.
I used a third bar button [Spacer] and set it to be [.flexiblewidth] Otherwise, when adding it only the left button appears [Cancel] and the [Spacer] & and [Save] which have to be next disappearing ?
the screen shot is in the link:
https://ibb.co/cZsaVV
let pickerView = UIPickerView()
override func viewDidLoad() {
pickerView.addSubview(self.setToolBar())
}
func setToolBar() -> UIToolbar {
let toolBar = UIToolbar()
toolBar.isTranslucent = true
toolBar.backgroundColor = UIColor.clear
let barButtonAttr = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 15),
NSAttributedString.Key.foregroundColor : UIColor.black]
// [Save] BarButtonItem
let saveBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.save, target: self, action: nil)
saveBarButtonItem.setTitleTextAttributes(barButtonAttr, for: .normal)
// [Cancel] BarButtonItem
let cancelBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.cancel, target: self, action: nil)
cancelBarButtonItem.setTitleTextAttributes(barButtonAttr, for: .normal)
let spacerBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace ,
target: self, action: nil)
spacerBarButtonItem.setTitleTextAttributes(barButtonAttr, for: .normal)
// add BarButtonItems to toolBar
toolBar.items = [cancelBarButtonItem,spacerBarButtonItem,saveBarButtonItem]
toolBar.sizeToFit()
return toolBar
}
func createAccessoryViewWithTarget(_ target: AnyObject, width: CGFloat) -> UIView {
// Previous button
let previousButton = UIBarButtonItem(title: "Previous", style: .plain, target: target, action: #selector(self.moveToPreviousTextField))
previousButton.tintColor = UIColor.white
//Next button
let nextButton = UIBarButtonItem(title: "Next", style: .plain, target: target, action: #selector(self.moveToNextTextField))
nextButton.tintColor = UIColor.white
// Dismiss/close/done button
let doneButton = UIBarButtonItem(title: "Done", style: .done, target: target, action: #selector(self.keyboardDoneButtonTapped))
doneButton.tintColor = UIColor.white
let keyboardToolbar: UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: width, height: 44))
keyboardToolbar.barStyle = .black
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let fixedSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
var itemsArray = [UIBarButtonItem]()
itemsArray.append(previousButton)
itemsArray.append(fixedSpace)
itemsArray.append(nextButton)
itemsArray.append(flexSpace)
itemsArray.append(doneButton)
keyboardToolbar.items = itemsArray
keyboardToolbar.sizeToFit()
return keyboardToolbar
}
This one is old code may be swift3 I guess. Here Im adding 3 buttons previous next and done button. flexible space and fixed space are used for spaces between buttons. Important to note here is the order that you adding your barbutton items. In your case use flexible space to place your 2 buttons on right and left end in the order of left end button, flexible space, right end button.
I've got the solution finally.
I am adding the ToolBar to the PickerView and then calling UIToolBar.SizeToFit() which is must in all cases.
the issue was I had to change the picker view size later in this case the size of subview ToolBar is not adapting with the new size coordination of pickerView. So the solution simply to call again ToolBar.SizeToFit() after any modification of parent view. here's snap of the code:
// popupView is custom UIPickerView
popupView.frame = CGRect(x:0, y:0, width:100, height:100)
// toolBar is an object of UIToolBar of the custom UIPickerView AddCurrencyPicker
(popupView as! AddCurrencyPicker).toolBar.sizeToFit()

Swift: How do I create a custom UINavigationBar and add a custom back button?

I am trying to create a custom navigationBar.
I am hiding the original navigationBar in viewWillAppear like so:
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.isNavigationBarHidden = true
}
I am subclassing UINavigationBar like so:
let navBar: UINavigationBar = {
let view = UINavigationBar()
view.backgroundColor = .clear
view.isTranslucent = true
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
In viewDidLoad I am calling setupNavBar():
func setupNavBar() {
view.addSubview(navBar)
self.navBar.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 80)
let backButton = UIBarButtonItem(image: UIImage(named:"backThick"), style: .plain, target: self, action: #selector(popControllerOffStack))
}
The problem is that backButton is added to the original navigationBar that is being hidden. This makes me think I am incorrectly creating the navigationBar. How do I add the button to navBar?
Updated Code (still not working):
class CustomNavBar: UINavigationBar {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = .red
}
}
// In the viewController
let navBar = CustomNavBar()
override func viewDidLoad() {
super.viewDidLoad()
setupNavBar()
}
func setupNavBar() {
view.addSubview(navBar)
navBar.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 80)
let backButton = UIBarButtonItem(image: UIImage(named:"backThick"), style: .plain, target: self, action: #selector(popControllerOffStack))
self.navigationItem.leftBarButtonItem = backButton
}
The button is being added to the original navigationBar.
You are not subclassing UINavigationBar. Rather, you are creating a new instance of UINavigationBar and modifying its properties inside a computed variable. This means each time you access navBar, you are initializing a new UINavigationBar object.
To create a subclass:
class MyCustomNavigationBar: UINavigationBar {
// Set properties in here after initialization
}
Once you have a proper subclass created, You can initialize an instance like so:
var navBar = MyCustomNavigationBar()
Finally, add your button to the navigation bar:
let backButton = UIBarButtonItem(image: UIImage(named:"backThick"), style: .plain, target: self, action: #selector(popControllerOffStack))
// Assuming 'self' is an instance of UINavigationController()
self.navigationItem.leftBarButtonItem = backButton
See the official Swift Programming Language Guide on Inheritance.
Swift 3.0
You can set custom Back button as like below
self.navigationItem.hidesBackButton = true
let backButton = UIBarButtonItem(image: UIImage(named: "image_name"), style: .plain, target: self, action: #selector(Class.methodName))
backButton.tintColor = UIColor.white
self.navigationItem.leftBarButtonItem = backButton
Also you can try below code:
let btnLeftMenu: UIButton = UIButton()
btnLeftMenu.setImage(UIImage(named: "image_name"), for:UIControlState())
btnLeftMenu.addTarget(self, action: #selector(moveImage), for:UIControlEvents.touchUpInside)
btnLeftMenu.frame = CGRect(x: 0, y: 0, width: 25, height: 25)
let barButton = UIBarButtonItem(customView: btnLeftMenu)
self.navigationItem.leftBarButtonItem = barButton*

Space issue with UIBarButtonItem

I am trying to add a Cancel UIBarButtonItem to my navigation bar using following code:
func setupNavBar() {
self.navBar = UINavigationBar(frame: CGRectMake(0.0, 0.0, UIScreen.mainScreen().bounds.width, 64.0))
let customNavigationItem = UINavigationItem(title: "Connect Accounts")
let cancelButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: "cancelClicked")
customNavigationItem.setLeftBarButtonItem(cancelButton, animated: true)
self.navBar.setItems([customNavigationItem], animated: true)
self.view.addSubview(self.navBar)
}
The bar button is appearing completely sticked to the screen edge as follow:
Why is this button appearing sticked to the edge of screen and how can I give it spacing so that it does not sticks there? Please help!
EDIT: My button is sticked to just left edge of screen and not to the top-left corner.
The correct way to add space is using .FixedSpace :
let fixedSpace = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil, action: nil)
fixedSpace.width = 10
customNavigationItem.leftBarButtonItems = [fixedSpace, cancelButton]
UIBarButtonSystemItemFixedSpace
Blank space to add between other
items. Only the width property is used when this value is set.
Available in iOS 2.0 and later.
Try this
let btn = UIButton(frame: CGRectMake(<your margin>, 0, 50, 44))
btn.setTitle("Cancel", forState: UIControlStateNormal)
let btnbarButton = UIBarButtonItem(customView: btn)
customNavigationItem.setLeftBarButtonItem(btnbarButton, animated: true)
Try it.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.setupNavBar()
}
func setupNavBar() {
let navBar = UINavigationBar(frame: CGRectMake(0.0, 0.0, UIScreen.mainScreen().bounds.width, 64.0))
let customNavigationItem = UINavigationItem(title: "Connect Accounts")
let cancelButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: "cancelClicked:")
let fixedSpace = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil, action: nil)
fixedSpace.width = 10
customNavigationItem.leftBarButtonItems = [fixedSpace, cancelButton]
navBar.setItems([customNavigationItem], animated: true)
self.view.addSubview(navBar)
}
func cancelClicked(sender: AnyObject){
print("Good luck!")
}

iOS rightBarButtonItem on UINavigationController in swift

I'm trying to put a rightBarButtonItem on a second view controller of an UINavigationViewController stack.
I'm creating and setting the button in viewDidLoad of the view controller that I want to show. My actual code looks like this:
override func viewDidLoad() {
super.viewDidLoad()
menu_button_ = UIBarButtonItem(image: UIImage(named: "menu"),
style: UIBarButtonItemStyle.Plain ,
target: self, action: "OnMenuClicked:")
self.navigationController!.navigationItem.rightBarButtonItem = menu_button_
}
What am I missing? The button doesn't appear.
You should set the menu_button_ as the rightBarButtonItem of your viewController rather than the navigationController.
Try
self.navigationItem.rightBarButtonItem = menu_button_
instead of
self.navigationController!.navigationItem.rightBarButtonItem = menu_button_
try with following code. it works for me.
let homeButton : UIBarButtonItem = UIBarButtonItem(title: "LeftButtonTitle", style: UIBarButtonItemStyle.Plain, target: self, action: "")
let logButton : UIBarButtonItem = UIBarButtonItem(title: "RigthButtonTitle", style: UIBarButtonItemStyle.Plain, target: self, action: "")
self.navigationItem.leftBarButtonItem = homeButton
self.navigationItem.rightBarButtonItem = logButton
And if you want to settle out custom image then please check with apple guidelines on below link.
https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/BarIcons.html#//apple_ref/doc/uid/TP40006556-CH21-SW1
In Swift 5
//For righter button item
let rightBtn = UIBarButtonItem(image: UIImage(named: "rightmenu"), style: .plain, target: self, action: #selector(onClickMethod))//Change your function name and image name here
self.navigationItem.rightBarButtonItem = rightBtn
//self.navigationItem.rightBarButtonItem = [rightBtn, anotherBtn] //If you want to add more buttons add like this
//This is your function
#objc func onClickMethod() {
print("Left bar button item")
}
Create an extension of UINavigationItem like -
extension UINavigationItem {
func addSettingButtonOnRight(){
let button = UIButton(type: .custom)
button.setTitle("setting", for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 15.0)
button.layer.cornerRadius = 5
button.backgroundColor = .gray
button.frame = CGRect(x: 0, y: 0, width: 100, height: 25)
button.addTarget(self, action: #selector(gotSettingPage), for: UIControlEvents.touchUpInside)
let barButton = UIBarButtonItem(customView: button)
self.rightBarButtonItem = barButton
}
#objc func gotSettingPage(){
}
}
And call it from viewDidLoad() like -
self.navigationItem.addSettingButtonOnRight()

Resources