This question already has answers here:
on single tap UIBarButton display toast and on double tap back action need to perform
(3 answers)
Closed 4 years ago.
I'm trying to implement a custom back button for every ViewController in my app. I want it to have two actions. If the button gets single tapped, it should give toast warning. If the button gets double tapped it should go back to ViewController.
How can I achieve this for only the backbutton in swift?
Try this to Work with bar Button with single and Double Tap
/// Tap Gesture to Handle Double Tap
let tapGesture : UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(SourceVC.handleGesture(getsure:)))
tapGesture.numberOfTapsRequired = 2
/// Custom Button That With Handle two actions
let customButtonn : UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
customButtonn.setTitleColor(UIColor.blue, for: .normal)
customButtonn.setTitle("button", for: .normal)
customButtonn.addTarget(self, action: #selector(SourceVC.navButton(sender:)), for: .touchUpInside)
customButtonn.addGestureRecognizer(tapGesture)
/// Create a Custom bar Button
let navLeftButton = UIBarButtonItem()
navLeftButton.customView = customButtonn
/// Assign it to navigation Bar
self.navigationItem.leftBarButtonItem = navLeftButton
My custom Button Actions in SourceVC Class
/// Single Tap
#objc func navButton(sender:UIButton){
print("navButtonTapped Once")
}
/// Double Tap
#objc func handleGesture(getsure:UITapGestureRecognizer){
print("navButtonTapped twice")
}
Simulator Output:
Console output:
Note - Doing this will move default back occur with the bar and you need to design it custom way so it appear like that as Shown in Simulator output - button appear without that back image
You cannot modify the actions and behavior for BackBarButtonItem, what you can do is create a your own UIBarButtonObject and assign it as your leftBarButtonItem while giving it your own selector
One thing to note is that this will remove the stock back button image.
Try this:
let doubleTap = UITapGestureRecognizer(target: self, action: #selector(actingFunction))
DoubleTap.numberOfTapsRequired = 2
barButton.addGestureRecognizer(doubleTap)
Related
There was many guys who meet problem with absence of Done button in numeric keyboard for iOS and there are many solutions to do it. I create this button but I cant find way to set focus on next text field by hit on this button. In my case there code that generates Table with TableViewCells. Thats why common idea to create reference to every Cell (anyway there are many cells). Every TableViewCell include ContentView and ContentView include TextField.
As result my custom Done button should behave like Return button in standard keyboard. By the way there method in textFieldShouldReturn that change focus but textFieldShouldReturn invoked on built-in Return button.
P.S. Im new in Swift.
Note: I have created a sample project where the next button functionality is implemented. You can find the project: https://github.com/nasirky/uitableview-form
You can add a toolbar with a done button to the UITextField inputAccessoryView. Here is an example
override func viewDidLoad() {
super.viewDidLoad()
textField.inputAccessoryView = getToolbar()
}
func getToolbar() -> UIToolbar {
let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 40))
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action:#selector(doneAction(_:)))
toolBar.setItems([doneButton], animated: false)
return toolBar
}
func doneAction(_ sender: UIBarButtonItem) {
/* Code for dismissing keyboard or moving focus to next UITextField */
}
After I carefully rechecked existing jump function I put it into textFieldDidEndEditing event. Inside Done function (doneAction in Nasir`s example) I put self.endEditing(true)
I am using SWRevealViewController for side menu and IQKeyboardManagerSwift for keyboard.
When I am editing content in textfield and tries to open menu, the keyboard should automatically hide but I can't manage to do so.
How should this be done?
Capture the event of the opening menu. You can do this with SWRevealViewcontroller Delegate or by simply adding an #IBAction to the menu button.
In this method call .resignFirstResponder() for the element that needs the keyboard (like a textField):
textField.resignFirstResponder()
Of course you can call this function in every element that can have a keyboard to be sure to call the right one.
Since UIBarButtonItem doesn’t inherit from UIView or expose the item’s underlying view, this isn’t as easy as adding a gesture recognizer.
One plausible solution would be to [Step 1] define a custom view for the Side Menu Icon [Step 2]add the gesture to hide keyboard to it.
//gesture:tap anywehere to dismiss the keyboard
let tap = UITapGestureRecognizer(target:self.view,action:#selector(UIView.endEditing))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
let customButton = UIButton(frame: CGRect.init(x: 0, y: 0, width: 20, height: 20))
customButton.setImage(UIImage(named: "menu"), for: .normal)
//hide keyboard gesture(tap gesture)
customButton.addGestureRecognizer(tap)
customButton.isUserInteractionEnabled = true
if self.revealViewController() != nil {
customButton.addTarget(self.revealViewController(), action: #selector(SWRevealViewController.revealToggle(_:)), for: .touchUpInside)
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
self.navigationItem.leftBarButtonItem?.customView = customButton
Please accept as answer if it works.(Worked for me)
I'm new to Swift and I'm trying to change the button colour on tap. When the button is tapped, it should change colour and when released it should go back to the original button colour.
An example of this is the calculator. When you tap a button, it changes from light grey to dark grey and when the user removes their finger off the button, it goes back to the original light grey colour. How do I go about doing that?
So far, I've only got this..
#IBAction func changeButtonColourOnTouch(sender: UIButton) {
zeroButton.backgroundColor = UIColor.blueColor()
}
The above code changes the button colour to blue but stays blue.
The problem is, after releasing the button, you should return the color to the original state.
You can link direct from storyboard, in the action TouchUpInside (release) and TouchDown (press) , to change the button color to the correct state in each event.
Or you can add a Target in the button by code, linking to the functions, as the code bellow shows it.
zeroButton.addTarget(self, action: Selector("holdRelease:"), forControlEvents: UIControlEvents.TouchUpInside);
zeroButton.addTarget(self, action: Selector("HoldDown:"), forControlEvents: UIControlEvents.TouchDown)
//target functions
func HoldDown(sender:UIButton)
{
zeroButton.backgroundColor = UIColor.blueColor()
}
func holdRelease(sender:UIButton)
{
zeroButton.backgroundColor = UIColor.whiteColor()
}
Code adapted by the present in the link UIButton with hold down action and release action
The checked answer above works, but if the user holds down on the button, then drags out, the background color won't return to normal. It's a tiny UI bug, but a simple fix. This includes the code of the checked answer.
zeroButton.addTarget(self, action: #selector(holdRelease), for: .touchUpInside);
zeroButton.addTarget(self, action: #selector(heldDown), for: .touchDown)
zeroButton.addTarget(self, action: #selector(buttonHeldAndReleased), for: .touchDragExit)
//target functions
#objc func heldDown()
{
zeroButton.backgroundColor = .blue
}
#objc func holdRelease()
{
zeroButton.backgroundColor = .white
}
#objc func buttonHeldAndReleased(){
zeroButton.backgroundColor = .blue
}
you could also use a tap gesture and change the color of the button as the user is tapping on the button
you could see apple documentation regarding UIGestureRecognizer in here
it is a little bit advanced, but you will learn a lot from it.
You can also use setbackgroundImageForState to define color image as button background for all UIControlState you are interested in e.g. Normal, Highlighted, Disabled, Selected.
let cx = UIGraphicsGetCurrentContext()
let color = UIColor.redColor()
let state = UIControlState.Selected
UIGraphicsBeginImageContext(CGSize(width:1, height:1))
CGContextSetFillColorWithColor(cx, color.CGColor)
CGContextFillRect(cx, CGRect(x:0, y:0, width:1, height:1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.zeroButton.setBackgroundImage(colorImage, forState: state)
Now color changes automatically and you don't have to handle it manually.
If you want that for a programmatically defined button, just declare the button of type system during its initialisation:
let button = UIButton(type: .system)
It's a simple question,
I have a UIButton with a target action
addTarget(self, action: "buttonPressed", forControlEvents: UIControlEvents.TouchUpInside)
func buttonPressed()
{
self.selected = !self.selected
}
This button is the child of a parent UIView
containerView.addSubview(button)
I add a UITapGestureRecognizer to the container
let tapG = UITapGestureRecognizer(target: self, action: "toggleView:")
containerView.addGestureRecognizer(tapG)
in func toggleView(gest:UIGestureRecognizer) I check the status of my button.
The problem is that in toggleView(), the status of the button has not been set... YET!
EDIT
if I do
print(button.selected)
I only get the button value BEFORE the touch event, not the new one.
any idea?
Try to change
func toggleView(gest:UIGestureRecognizer)
to
func toggleView(gest:UITapGestureRecognizer)
Hope it helps!
I don't exactly get what you are trying to accomplish, If you want to perform certain action on button click and another action when tapped outside in containerView then you can do
-(void)toggleView:(UITapGestureRecognizer *) gest{
CGPoint tapLocation = [gest loactionInView:containerView];
if(CGRectContainsPoint(button.frame, tapLocation)){
// Tapped on Button
}
else{
// tapped outside in containerView
}
}
Note: As am not learning swift, i gave snippet in Objective-C. you should be able to translate it into swift easily :)
I am trying to get a UIButton to repeat the code over and over until the user releases the button. I have an up arrow in a game and when it is tapped, a space ship will go up until it is released. Here is the code for my button:
//at top of page
let upArrow = UIButton()
//in viewdidload()
let upArrowImage = UIImage(named: "upArrow") as UIImage?
upArrow.setImage(upArrowImage, forState: .Normal)
upArrow.frame = CGRectMake(10, 220, 90, 40)
upArrow.addTarget(self, action: "upArrowTouched:", forControlEvents: UIControlEvents.TouchUpInside)
self.view?.addSubview(upArrow)
//outside of viewDidLoad()
func upArrowTouched(sender:UIButton!){
spaceship.position = CGPointMake(spaceship.position.x, spaceship.position.y + 3)
}
Any suggestions??
You need to implement your own solution for this, something along the lines
1- User touches down (UIControlEvent touchDown), you start a time that fires every x secs/millisecs
2- Timer will fire the action over and over
3- User touches up UICOntrolEvent touchUp, you cancel your timer
So you bind those 2 events to different functions, and start/kill your timers with appropriate actions
How that helps
Daniel