Change title of a navigation bar button item - ios

let button = UIButton()
button.setImage(UIImage(named: "coin_icon"), forState: UIControlState.Normal)
button.addTarget(self, action:#selector(Profile.goCoin), forControlEvents: UIControlEvents.TouchDragInside)
button.frame=CGRectMake(0, 0, 30, 30)
let barButton = UIBarButtonItem(customView: button)
self.navigationItem.rightBarButtonItem = barButton
My code is this to add a bar button on navigation bar.
However, i need to change the title of button in a function
func changetitle() {
self.navigationItem.rightBarButtonItem?.title = "Change"
}
I tried this one but didn't work.
How can i change the title of this button?

You need to access the UIButton from the UIBarButtonItem and change the title of the UIButton.
func changetitle() {
let item = self.navigationItem.rightBarButtonItem!
let button = item.customView as! UIButton
button.setTitle("Change", for: .normal)
}

Related

Keep track of which UITextField is currently in editing mode

In the following code I have a couple buttons showing as an inputAccessoryView when inputFieldOne is in editing mode, when you tap First Button, it inputs ONE inside inputFieldOne and when I tap Second Button it inputs TWO inside inputFieldOne. It works as expected but what I would like to be able to do is re-use these buttons in multiple UITextFields. In other words, if I have another UTTextField called inputFieldTwo, I would like to be able to also input the values from those buttons when they're tapped.
How can I keep track of what UITextField is currently in editing mode so I can append the values from the buttons?
#IBOutlet weak var inputFieldOne: UITextField!
#IBOutlet weak var inputFieldTwo: UITextField!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
addButtonsToKeyboard()
}
func addButtonsToKeyboard(){
// First button
let button1 = UIButton()
button1.setTitle("First Button", for: UIControl.State())
button1.addTarget(self, action: #selector(buttonKeyPress), for: UIControl.Event.touchUpInside)
let barButton1 = UIBarButtonItem()
barButton1.customView = button1
// Second button
let button2 = UIButton()
button2.setTitle("Second Button", for: UIControl.State())
button2.addTarget(self, action: #selector(buttonKeyPress), for: UIControl.Event.touchUpInside)
let barButton2 = UIBarButtonItem()
barButton2.customView = button2
/// UIToolbar.
let toolBar = UIToolbar()
toolBar.tintColor = UIColor.blue
toolBar.barTintColor = UIColor.red
toolBar.items = [barButton1, barButton2]
toolBar.sizeToFit()
inputFieldOne.inputAccessoryView = toolBar
}
#objc func buttonKeyPress(_ sender: UIButton){
switch sender.currentTitle!{
case "First Button":
inputFieldOne.text = "ONE"
case "Second Button":
inputFieldOne.text = "TWO"
default: break
}
}
There are many ways to make it reusable as i have very limited time so i suggest you can do it with Extension
You can use it for you all textfield
So here is the code snippet:
extension UITextField
{
// you can pass here array of UIbarbutton also
func addButtonsToKeyboard(){
// First button
let button1 = UIButton()
button1.setTitle("First Button", for: UIControl.State())
button1.addTarget(self, action: #selector(buttonKeyPress), for: UIControl.Event.touchUpInside)
let barButton1 = UIBarButtonItem()
barButton1.customView = button1
// Second button
let button2 = UIButton()
button2.setTitle("Second Button", for: UIControl.State())
button2.addTarget(self, action: #selector(buttonKeyPress), for: UIControl.Event.touchUpInside)
let barButton2 = UIBarButtonItem()
barButton2.customView = button2
/// UIToolbar.
let toolBar = UIToolbar()
toolBar.tintColor = UIColor.blue
toolBar.barTintColor = UIColor.red
toolBar.items = [barButton1, barButton2]
toolBar.sizeToFit()
self.inputAccessoryView = toolBar
}
#objc func buttonKeyPress(_ sender: UIButton){
switch sender.currentTitle!{
case "First Button":
self.text = "ONE"
case "Second Button":
self.text = "TWO"
default: break
}
}
}
And with you textfield object you can add it with below code
txtSwift.addButtonsToKeyboard()
Hope it help you!!!

Hide UIbutton before I jump into other state

UIbutton remove from MenuScene before I jump into GameScene, or when I don't remove, the button is visible in GameScene, but I draw in MenuScene, why is that? What is the best way to create buttons and change the images of button?
The code is:
var button: UIButton!
button = UIButton()
var buttonFrame = self.view!.frame
button?.frame = CGRectMake(0, 0, 200, 100)
let buttonImage = UIImage(named: "PlayButton")
let buttonClick = UIImage(named: "PlayButton-click")
button!.setImage(buttonImage, forState: UIControlState.Normal)
button!.setImage(buttonClick, forState: UIControlState.Highlighted)
button!.addTarget(self, action: "PlayButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
self.view?.addSubview(button)
func PlayButtonClick(sender: UIButton) {
self.view?.presentScene(GameScene(size:self.size),transition: .crossFadeWithDuration(1.2))
button.removeFromSuperview()
}
Try that in PlayButtonClick Method:
sender.hidden = true
This should probably do the trick.
button.hidden = true, or sender.hidden = true,
This hide the uibutton , but button is hide very early, before i enter the GameScene state, and i see that..

Hide Title of Button in ios Swift and show image instead

I want to hide the Label text of a button onClick and instead show an image.
On a second click, the title should appear again.
Sadly, the title disappears and the color of the button changes but there is no image shown and on click it never enters the "else"-Part of the if/else where the label should appear back again, so "2" is never printed.
What is the error?
if (button10.titleLabel!.text != "") {
print("1")
button10.setTitle("", forState: .Normal)
button10.setImage(UIImage(named: "1.png"), forState: UIControlState.Normal)
}
else if (button10.titleLabel!.text == ""){
print("2")
button10.setTitle("String", forState: .Normal)
}
You need to remove/change the image for the button too:
#IBOutlet weak var button: UIButton!
var clicked = false
#IBAction func buttonClicked(sender: AnyObject) {
if (clicked){
clicked = false
button.setTitle("", forState: .Normal)
button.setBackgroundImage(UIImage(named: "black"), forState: UIControlState.Normal)
}
else{
clicked = true
button.setBackgroundImage(UIImage(named: ""), forState: UIControlState.Normal)
button.setTitle("Clicked", forState: .Normal)
}
}
And to change the image for a UIButton use setBackgroundImage

Select/deselect buttons swift xcode 7

Part way done with learning swift but I hit a small wall and yet again, I'm sure I'm just a bit new at this and an easy solution is there but I'm having trouble figuring out how to select/deselect buttons below is what I have so far and it is a button turns into a checkmark when clicked on... I've gotten that far but I need that button to deselect when clicked on again and then obviously be able to be clicked again if need be.
#IBAction func buttonPressed(sender: AnyObject) {
sender.setImage(UIImage(named: "Checkmark.png"), forState: .Normal)
}
Swift 3 note: .selected and .checked are now lower case UIControlState values in the SDK, and some of the methods have been renamed:
let button = UIButton()
button.setImage(UIImage(named: "Unchecked"), for: .normal)
button.setImage(UIImage(named: "Checked"), for: .selected)
You can also now use image literals with Xcode 8 instead of UIImage(named:):
#imageLiteral(resourceName: "Unchecked")
Swift 2:
Why not use the .Selected state of the button as the "checked" state, and the .Normal state as the "unchecked" state.
let button = UIButton()
button.setImage(UIImage(named: "Unchecked"), forState: .Normal)
button.setImage(UIImage(named: "Checked"), forState: .Selected)
// ...
#IBAction func buttonPressed(sender: AnyObject) {
if let button = sender as? UIButton {
if button.selected {
// set deselected
button.selected = false
} else {
// set selected
button.selected = true
}
}
}
You dont need to set selected in condition. I just doing with following method in swift:
func selectDeselect(sender: UIButton){
sender.selected = !sender.selected
if(sender.selected == true)
{
sender.setImage(UIImage(named:"select_heart"), forState: UIControlState.Normal)
}
else
{
sender.setImage(UIImage(named:"heart"), forState: UIControlState.Normal)
}
}
Here is Working code for swift 4.
Make Sure you need to connect Button IBAction Outlet as UIButton and set default button image from storyboard whatever you want.
#IBAction func btnTapped(_ sender: UIButton) {
if sender.currentImage == UIImage(named: "radio_unchecked"){
sender.setImage(UIImage(named: "radio_checked"), for: .normal)
}else{
sender.setImage(UIImage(named: "radio_unchecked"), for: .normal)
}
}
update for Swift 4+ :
let button = UIButton()
button.setImage(UIImage(named: "Unchecked"), forState: .Normal)
button.setImage(UIImage(named: "Checked"), forState: .Selected)
#IBAction func buttonPressed(sender: AnyObject) {
if let button = sender {
if button.isSelected {
// set deselected
button.isSelected = false
} else {
// set selected
button.isSelected = true
}
}
}
Set uncheck image on default state from storyboard and check image on selected state from storyboard.
#IBAction func buttonPressed(sender: AnyObject) {
buttonOutlet.isSelected = !buttonOutlet.isSelected
}
private(set) lazy var myButton: UIButton = {
let button = UIButton()
button.setImage(UIImage(named: "Unchecked"), for: .normal)
button.setImage(UIImage(named: "Checked"), for: .selected)
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
#objc
func buttonTapped(sender: AnyObject) {
sender.isSelected.toggle()
}
To select only the pressed button out of three buttons and deselect the others when designated button is pressed.
#IBAction func buttonPressed(_ sender: UIButton) {
// Deselect all buttons
button1.isSelected = false
button2.isSelected = false
button3.isSelected = false
// Select the pressed button
sender.isSelected = true
}

Swift properly aligns a UIBarButtonItem that was created programatically

I used the following tutorial to programmatically create a UIBarButtonItem in Swift, but the icon isn't properly aligned to the border. Here's the code for the button. Can anyone tell me how to modify the code below to properly align the UIBarButtonItem Image?
The 1st image shows the location of the programmatically created uibarbuttonitem, and the 2nd image shows the uibarbuttonitem created from storyboard. I want the programmatically created uibarbuttonitem to look like uibarbuttonitem created using storyboard. Thanks for the help!
var button: UIButton = UIButton()
button.setImage(UIImage(named: "leftArrow.png"), forState: .Normal)
button.frame = CGRectMake(0, 0, 40, 40)
button.targetForAction("actioncall:", withSender: nil)
var leftBarButtonItem:UIBarButtonItem = UIBarButtonItem()
leftBarButtonItem.customView = button
self.navigationItem.leftBarButtonItem = leftBarButtonItem
Also, how do I properly set the action for when the uibarbuttontiem is pressed? I tried the following but it's never called.
func actioncall(sender: AnyObject){
println("action")
}
Edit 1: I updated the code as follows thanks to agy's response.
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
if (cond){
var button: UIButton = UIButton()
button.setImage(UIImage(named: "leftArrow.png"), forState: .Normal)
button.frame = CGRectMake(0, 0, 40, 40)
button.addTarget(self, action: "actioncall:", forControlEvents: .TouchUpInside)
var leftBarButtonItem:UIBarButtonItem = UIBarButtonItem()
leftBarButtonItem.customView = button
var negativeSpacer:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil)
negativeSpacer.width = -20; // set the value you need
self.navigationItem.leftBarButtonItems = [negativeSpacer,leftBarButtonItem]
}
}
func actioncall(sender: UIButton!){
println("action")
}
but the action still fails. The app crashes when I press the uibarbuttontiem and I get the following error message
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[AppName.ProfileViewController actioncall:]: unrecognized selector sent to instance 0x7a07a470'
What's the correct function for the action?
Edit 2: The actioncall is in the same class as where I'm creating the UIBarButtonItem. I'm setting the leftbarbutton on viewwillappear because depending on who views this viewcontroller, the option to go back will replace the previous option located on the leftbarbutton.
Try adding a negative spacer, and change the method targetForAction for addTarget:
var button: UIButton = UIButton()
button.setImage(UIImage(named: "leftArrow.png"), forState: .Normal)
button.frame = CGRectMake(0, 0, 40, 40)
button.addTarget(self, action: "actioncall:", forControlEvents: .TouchUpInside)
var leftBarButtonItem:UIBarButtonItem = UIBarButtonItem()
leftBarButtonItem.customView = button
var negativeSpacer:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil)
negativeSpacer.width = -5; // set the value you need
self.navigationItem.leftBarButtonItems = [negativeSpacer,leftBarButtonItem]
func actioncall(sender: UIButton!){
print("Called")
}

Resources