Custom UIButton class, is there a was clicked event? - ios

I'm trying to make a custom UIButton class called BubbleButton. It will perform some animations when the button is clicked and released. Are there methods that I can put in that will be called when the button is pressed or released? Such as didClicked or something like that?

There are only (really) two that you should be worried about, setSelected and setHighlighted. setHighlighted is called immediatly after the button is pressed and setSelected is called if you hold the button for like 1/2 a second. There is also a focused state but thats not really relevant. Here is an example of a UIButton I subclasssed:
-(void)drawRect:(CGRect)rect{
[super drawRect:rect];
//Set unhighlighted state
if (self.highlighted) {
//Set highlighted state
}
}
-(void)setHighlighted:(BOOL)highlighted {
[super setHighlighted:highlighted];
[self setNeedsDisplay];
}

Related

Show UITableView after UIButton was tapped

I have a UITableView that i would like to hide until the user taps the button searchButtonTapped. (I'm also using this button as an IBAction.)
Originally i'm hiding the table view as you see in the viewDidLoad, and i wanna show it after the button was tapped, but it does not shown up after i tap the search button. Do i missed something? For me, it seems it should be work properly, after the button was tapped i refresh the table view.
my .h file
#property (weak, nonatomic) IBOutlet UIButton *searchButtonTapped;
- (IBAction)searchButton:(id)sender;
.m file
- (void)viewDidLoad
{
[super viewDidLoad];
self.tableView.hidden = YES;
}
- (void)buttonTapped:(id)sender {
if (sender == self.searchButtonTapped) {
self.tableView.hidden = NO;
[self.tableView reloadData];
}
}
- (IBAction)searchButton:(id)sender {
[self searchSetup];
}
It's impossible to tell from the little bit of code that you posted. Add NSLog statements in your buttonTapped method that show entering the method, entering the if statement, the value of searchButtonTapped, and the value of self.tableView.
Then you can tell if the method is getting called, if the if statement is evaluating as true, and if the table view is non-nil. One of those things is likely to be the cause of your problem.
I'm guessing that the if statement is wrong. what type is the property self.searchButtonTapped? Post the code that declares that property.
Based on the name I would guess that searchButtonTapped is a boolean?
you have declared only one IBAction, which is for the method searchButton.
This method call the searchSetup´s method. What is the purpose of it?
- (IBAction)searchButton:(id)sender {
[self searchSetup];
}
So you must have another IBAction for buttonTapped method witch is currently a "void" method and not a IBAction. Or you make that connection from the storyBoard, or you must declare it programaticly like:
[self.searchButtonTapped addTarget:self action:#selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside]

Dismiss the keyboard with MULTIPLE UITextFields?

Is it possible to dismiss the keyboard when you have MULTIPLE UITextFields ? If so how ?
As a side note, do I have to dismiss the keyboard for Each and Every field or can it be done globally ? Oh and it would be super cool if I don't have to touch the DONE button, I'd ideally like a solution that where the user touches anything BUT the field in question and the keyboard automagically disappears...
Oh and if you'd be so kind step by step instructions.
I should have added that I have a method already to resign the keyboard....
However, it only runs when my form is submitted! (see method below)
My question is how to the keyboard to hide/dismiss without having to jump thru so many damned hoops! You'd figure after 6 years, a mature operating system would have a way to GLOBALLY hide the keyboard....NOT!
Ok, enough whining....
- (void)hideKeyboard {
[self.dancePlace resignFirstResponder];
[self.danceGate resignFirstResponder];
[self.danceTerminal resignFirstResponder];
[self.danceText resignFirstResponder];
[self.danceDate resignFirstResponder];
[self.danceStyle resignFirstResponder];
[self.danceTimeOut resignFirstResponder];
}
And this is called when my button is submitted....
- (IBAction)addListingPressed:(id)sender {
// NSLog(#"BUTTON PRESSED");
[self hideKeyboard];
[self valuesAdded];
}
My question, assuming anyone can answer this...and I suspect not, is there a way to globally hide the keyboard if the following conditions are MET: 1.) the user taps OUT of any one of the existing fields, 2.) presses anywhere else on the screen. 3.) Is no more than a line or two in the existing viewcontroller.m file. 4.) I don't have to add a confusing button on the viewcontroller. (any time I have to add outlets, the damned thing is crashing on me...and then nastiness happens, and really...remember I am JUST a beginner, and its very confusing to read that I have to place this here and that there...oy. Simple folks, simple. I'm not looking for elegant solution, just so that it works.
I have a super class that all my view controllers inherit from. In that class I have this code.
MySuperViewController.h
#import <UIKit/UIKit.h>
#interface MySuperViewController : UIViewController
#property(strong, nonatomic) UITapGestureRecognizer *backgroundTapGestureRecognizer;
#end
MySuperViewController.m
- (void)viewDidLoad{
//add a tap gesture recognizer to capture all tap events
//this will include tap events when a user clicks off of a textfield
self.backgroundTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(onBackgroundTap:)];
self.backgroundTapGestureRecognizer.numberOfTapsRequired = 1;
self.backgroundTapGestureRecognizer.cancelsTouchesInView = NO;
[self.view addGestureRecognizer:self.backgroundTapGestureRecognizer];
}
- (void)onBackgroundTap:(id)sender{
//when the tap gesture recognizer gets an event, it calls endEditing on the view controller's view
//this should dismiss the keyboard
[[self view] endEditing:YES];
}
I have the UITapGestureRecognizer as a public property, so I can override it if I need to.
subclass
MyViewController.h
#import <UIKit/UIKit.h>
#import "MySuperViewController.h"
#interface MyViewController : MySuperViewController<UIGestureRecognizerDelegate>
#end
MyViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
//You don't always want the keyboard to be dismissed, so you tie into the gesture recognizer's delegate method
//By doing this, you can stop the endEditing call from being made
[self.backgroundTapGestureRecognizer setDelegate:self];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
//touch.view is the view that recieved the touch
//if this view is another textfield or maybe a button, you can return NO and the endEditing call won't be made
if (touch.view == self.myViewThatShouldNotBeBlocked) {
return NO;
}
//if you want the gesture recognizer to accept the event, return yest
return YES;
}
I uploaded an example project to github.
https://github.com/JeffRegan/KeyboardBeGone
RDVKeyboardAvoiding is a scroll view with a tap gesture recognizer, designed for multiple textViews/textFields. It keeps track of the active view and removes a lot of boilerplate code.
tap anywhere outside the textField .. it will hide it..
[self.view endEditing:YES];
There are couple of other ways to do it.
[myEditField resignFirstResponder];
[myEditField endEditing];
[parentView endEditing];
If you dont wont to do so many things and simply want to dismiss keyboard than give iboutlet to each of your text filed to following method..
-(IBAction)hidekeyboard:(id)sender
{
[sender resignFirstResponder];
}
Yes, you only have to dismiss it for the one that is currently being edited.
In order to know which one is being edited, you can check the -(BOOL)isFirstResponder property, which will return YES if it is the first responder (the one being edited) or NO if it is not. Once you know which one is the first responder you can call -(void)resignFirstResponder on that one to get rid of the keyboard.
For example, if you have a method called -(void)aMethod that you want to dismiss the current view controller and you have an array of textViews called textArray, you could do a little loop such as:
-(void)aMethod {
for (UITextField *text in self.textArray) {
if ([text isFirstResponder]) [text resignFirstResponder];
return;
}
}
This way, you can have a variable number of textFields and it will still work.
If you only have one or two textFields and you do not want to create an Array object, you could do (assuming the fields are named text1 and text2:
-(void)aMethod {
if ([text1 isFirstResponder]) [text1 resignFirstResponder];
else if([text2 isFirstResponder]) [text2 resignFirstResponder];
}
Also, to make things easier for the future you could create a category method for UIView (which is what I do) to get the current first responder if it exists as a subview of that view:
#implementation UIView (GetFirstResponder)
- (UIView *)getFirstResponder {
if ([self isFirstResponder]) return self;
else {
for (UIView *subview in self.subviews) {
UIView *firstResponder = [subview getFirstResponder];
if (firstResponder) return firstResponder;
}
}
return nil;
}
You can put this method on the top of any file that you want to call it from, or create a separate file for it and import it.
Once you have this method, you can call:
- (void)aMethod {
UIView *view = [self.view getFirstResponder];
if (view) [view resignFirstResponder];
}
[superview endEditing:YES]; // superview can be the view controller's view property.

Understanding resignFirstResponder with UITextField

I'm trying to get rid of the keyboard when the user touch outside my UITextField, by using this method:
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[mainTextController resignFirstResponder];
[super touchesBegan:touches withEvent:event];
}
However, this seems to call a method that is called after pressing the return button on the keyboard, but I just want the keyboard to vanish, not to press return for me.
How can I accomplish that?
Thanks!
EDIT: tGilani's answer is the most straight-forward way, works like a charm, without changing to UIControl. But I guess jonkroll's answer also works.
try
[self.view endEditing:YES];
Update:
Take a boolean value and set it to false in init method. In your textFieldShouldReturn delegate method method, execute the code if it is false, skip otherwise
- (BOOL) textFieldShouldReturn:(UITextField*)textField
{
if (!boolean)
{
// YOur code logic here
}
boolean = false;
}
in your method where you call the endEditing method, set boolean to true.
boolean = YES;
[self.view endEditing:YES];
Here's how I've handled this before. First create a method on your view controller that will dismiss the keyboard by resigning first responder status on your text field:
- (IBAction)dismissKeyboard:(id)sender
{
[mainTextController resignFirstResponder];
}
Next, in your storyboard scene for your ViewController (or nib, if you are not using storyboards) change the class of your ViewController's view property from UIView to UIControl. The view property is effectively the background behind your other UI elements. The class type needs to be changed because UIView cannot respond to touch events, but UIControl (which is a direct subclass of UIView) can respond to them.
Finally, in your ViewController's viewDidLoad: method, tell your view controller to execute your dismissKeyboard method when the view receives a UIControlEventTouchDown event.
- (void)viewDidLoad
{
[super viewDidLoad];
UIControl *viewControl = (UIControl*)self.view;
[viewControl addTarget:self action:#selector(dismissKeyboard:) forControlEvents:UIControlEventTouchDown];
}
EDIT:
Part of your concern seems to be that textFieldDidEndEditing: is called when the keyboard is dismissed. That is unavoidable, it will always be called whenever a text field loses focus (i.e. first responder status). It sounds like your problem is that you have put code to perform when the user clicks the return button in textFieldDidEndEditing:. If you do not want that code to run when the user touches outside of the text field, that is not the proper place to put it.
Instead, I would put that code in a separate method:
- (IBAction)textFieldReturn:(id)sender
{
if ([mainTextController isFirstResponder]) {
[mainTextController resignFirstResponder];
// put code to run after return key pressed here...
}
}
}
and then call that method via Target-Action when your text field sends the control event UIControlEventEditingDidEndOnExit.
[mainTextController addTarget:self action:#selector(textFieldReturn:) forControlEvents:UIControlEventEditingDidEndOnExit];
Note that UIControlEventEditingDidEndOnExit is different than UIControlEventEditingDidEnd. The former is called when editing ends by the user touching outside the control, the latter is called when editing ends by the user pressing the return key.
You need to change your ViewController's view property from UIView to UIControl using the Identity Inspector:
From there, you simply create an IBAction and tell the textfield to dismiss (which I am assuming is your mainTextController). If mainTextController is not the textfield you want the keyboard to dismiss on then change the resignFirstReaponder method to your textfield like so.
- (IBAction)backgroundTap:(id)sender {
[myTextField resignFirstResponder];
}
then from there go back into your View Contoller's .xib file and connect the action to the Control View and select "Touch Down".

UITextField lose focus event

I have an UITextField in a MyCustomUIView class and when the UITextField loses focus, I'd like to hide the field and show something else in place.
The delegate for the UITextField is set to MyCustomUIView via IB and I also have 'Did End On Exit' and 'Editing Did End' events pointing to an IBAction method within MyCustomUIView.
#interface MyCustomUIView : UIView {
IBOutlet UITextField *myTextField;
}
-(IBAction)textFieldLostFocus:(UITextField *)textField;
#end
However, neither of these events seem to get fired when the UITextField loses focus. How do you trap/look for this event?
The delegate for the UITextField is set as MyCustomUIView so I am receiving textFieldShouldReturn message to dismiss the keyboard when done.
But what I'm also interested in is figuring when the user presses some other area on the screen (say another control or just blank area) and the text field has lost focus.
Try using delegate for the following method:
- (BOOL) textFieldShouldEndEditing:(UITextField *)textField {
NSLog(#"Lost Focus for content: %#", textField.text);
return YES;
}
That worked for me.
I believe you need to designate your view as a UITextField delegate like so:
#interface MyCustomUIView : UIView <UITextFieldDelegate> {
As an added bonus, this is how you get the keyboard to go away when they press the "done" or return buttons, depending on how you have set that property:
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
//This line dismisses the keyboard.
[theTextField resignFirstResponder];
//Your view manipulation here if you moved the view up due to the keyboard etc.
return YES;
}
The problem with the resignFirstResponder solution solely is, that it can only be triggered by an explicit keyboard or UITextField event.
I was also looking for a "lost focus event" to hide the keyboard, if somewhere outside the textfield was tapped on.
The only close and practical "solution" I came across is, to disable interactions for other views until the user is finished with the editing (hitting done/return on the keyboard) but still to be able to jump between the textfields to make corrections without the need of sliding out and in the keyboard everytime.
The following snippet maybe useful to someone, who wants to do the same thing:
// disable all views but textfields
// assign this action to all textfields in IB for the event "Editing Did Begin"
-(IBAction) lockKeyboard : (id) sender {
for(UIView *v in [(UIView*)sender superview].subviews)
if (![v isKindOfClass:[UITextField class]]) v.userInteractionEnabled = NO;
}
// reenable interactions
// assign this action to all textfields in IB for the event "Did End On Exit"
-(IBAction) disMissKeyboard : (id) sender {
[(UIResponder*)sender resignFirstResponder]; // hide keyboard
for(UIView *v in [(UIView*)sender superview].subviews)
v.userInteractionEnabled = YES;
}
You might have to subclass the UITextField and override resignFirstResponder. resignFirstResponder will be called just as the text field is losing focus.
i think you have implemented UIKeyboardDidHideNotification and in this event you
use code like
[theTextField resignFirstResponder];
remove this code.
also same code write in textFieldShouldReturn method. this also lost focus.
In Swift, you need to implement the UITextFieldDelegate to your ViewController and implement the method textFieldDidEndEditing from the delegate:
class ViewController: UIViewController, UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
// will be called when the text field loses their focus
}
}
Then you need to asign the delegate of your textField:
textField.delegate = self
For those struggling with this in Swift. We add a gesture recognizer to the ViewController's view so that when the view is tapped we dismiss the textfield. It is important to not cancel the subsequent clicks on the view.
Swift 2.3
override func viewDidLoad() {
//.....
let viewTapGestureRec = UITapGestureRecognizer(target: self, action: #selector(handleViewTap(_:)))
//this line is important
viewTapGestureRec.cancelsTouchesInView = false
self.view.addGestureRecognizer(viewTapGestureRec)
//.....
}
func handleViewTap(recognizer: UIGestureRecognizer) {
myTextField.resignFirstResponder()
}

drawRect not called for custom UIButton subclass when highlighted

When using drawRect for a custom UIButton subclass, it never seems to get called to draw the button when highlighted. Do I need to call setNeedsDisplay for my button in my touch events?
I found an easy solution.
Just add the following method to your UIButton subclass:
-(void)setHighlighted:(BOOL)highlighted
{
[super setHighlighted:highlighted];
[self setNeedsDisplay];
}
That's it!
As far as i can tell there is no straight forward way to subclass UIButton.
UIButton is not the actual class type that is returned by the initializers. UIButton is kind of a front for a series of private classes.
Say you had:
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
NSLog(#"myButton type: %#", [myButton description]);
You will find the type returned in the log to be "UIRoundedRectButton". The problem with that is you would need to have extended "UIRoundedRectButton". That is not possible as it is a private class which is only ever returned to UIButton.
On top of that "UIRoundedRectButton" is not the only possible returned class all of which are private.
In other words UIButton was built in manner that is not suited to be extended.
I had the same problem and satisfying success with the following added to my UIButton subclass
- (void)awakeFromNib {
[self addTarget:self action:#selector(redraw) forControlEvents:UIControlEventAllEvents];
}
- (void)redraw {
[self setNeedsDisplay];
[self performSelector:#selector(setNeedsDisplay) withObject:self afterDelay:0.15];
}

Resources