UITextField becomeFirstResponder triggers _resignFirstResponder - ios7

I am programatically creating a UITextField, adding it to view and then start editing by calling
[textField becomeFirstResponder];
But the issue is this call triggers call to textFieldDidEndEditing: delegate method. The stack trace points to [textField _resignFirstResponder] which is invoked by becomeFirstResponder. This is happening on simulator and iOS 7. How do I avoid this ? This is causing lot of issues as I don't want textFieldDidEndEditing: to be called without keyboard getting dismissed.
EDIT : Here is how I create UITextField.
UITextField *titleField = [[[UITextField alloc] init] autorelease];
[titleField addTarget:self action:#selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
titleField.textColor = [UIColor colorWithWhite:1.f alpha:0.8];
titleField.font = [UIFont fontWithName:#"HelveticaNeue-Medium" size:40.f];
titleField.textAlignment = NSTextAlignmentCenter;
titleField.borderStyle = UITextBorderStyleBezel;
titleField.autocorrectionType = UITextAutocorrectionTypeNo;
// titleField.borderStyle = UITextBorderStyleLine;
titleField.frame = CGRectMake(0, 0, 200, 80);
titleField.center = self.previewView.center;
titleField.delegate = self;
NSDictionary *titleDictionary = [self titleDictionary];
if (titleDictionary) {
titleField.text = [titleDictionary objectForKey:kTitleStringKey];
NSString *fontName = [titleDictionary objectForKey:kTitleFontNameKey];
CGFloat fontSize = [[titleDictionary objectForKey:kTitleFontSizeKey] floatValue];
titleField.font = [UIFont fontWithName:fontName size:fontSize];
NSData *textColorData = (NSData *)[titleDictionary objectForKey:kTitleTextColorKey];
titleField.textColor = [NSKeyedUnarchiver unarchiveObjectWithData:textColorData];
CGSize size = [titleField.text sizeWithFont:titleField.font];
titleField.frame = CGRectMake(0, 0, size.width + 40, 80);
titleField.center = self.previewView.center;
}
[self.view addSubview:titleField];
[titleField becomeFirstResponder];

Ok I found it. I had a UILongPressGestureRecognizer that triggered adding UITextField routine, and that is incidentally called twice on long press (need to figure out why, but its a separate issue). So becomeFirstResponder was called twice.

Related

Create a temporary HUD popup notification in Cocoa App

Im trying to have a window pop up to notify the user of an action, kind of like how the Flutter app shows a play/pause notification when a gesture is received.
This comes up for about two seconds and vanishes. The app itself is run from the menu bar so this pop up doesn't take control from whatever application is currently in focus but rather just shows on top of it and cannot be interacted with. I basically want to recreate exactly this. Say in the body of
- (void)popup:(id)sender {}
This is essentially very similar to a toast on android.
Edit: I looked closer at the flutter app and all it does is display two images (.png) one for the huge pause and another to indicate what application its in (in this case iTunes). Question now is how do I display an image like this.
You should take a look at this:
https://github.com/Foxnolds/MBProgressHUD-OSX
or Growl:
http://growl.info/documentation/developer/
To replicate this I added a 'HUD Window" from the interface builder which is just an NSPanel. I then added a image view to the panel and set the panel's colour to clear. I was then able to position the panel where I wanted and overlay the appropriate image.
I'm using this code:
static void showHud(NSString* text, int width, int height, CGFloat duration, int fontSize) {
NSWindow* window = [NSWindow new];
[window setFrame:NSMakeRect(0,0,width,height) display:NO];
[window center];
window.titleVisibility = NSWindowTitleHidden;
window.styleMask = NSWindowStyleMaskBorderless;
window.alphaValue = 0.9;
window.movableByWindowBackground = YES;
[window setLevel: NSStatusWindowLevel];
[window setBackgroundColor: [NSColor clearColor]];
[window setOpaque:NO];
//[window setHasShadow:NO];
[window makeKeyAndOrderFront:NSApp];
NSVisualEffectView *view = [[NSVisualEffectView new] initWithFrame:window.contentView.bounds];;
view.translatesAutoresizingMaskIntoConstraints = NO;
[view setBlendingMode:NSVisualEffectBlendingModeBehindWindow];
[view setMaterial:NSVisualEffectMaterialDark];
[view setState:NSVisualEffectStateActive];
//[view setAppearance:[NSAppearance appearanceNamed:NSAppearanceNameVibrantDark]];
//[view setWantsLayer:NO];
[view setWantsLayer:YES];
view.layer.cornerRadius = 16.;
//view.layer.shouldRasterize = YES;
//view.layer.rasterizationScale = 0.45;
view.layer.shadowOpacity = 0.1; //0.01;
view.layer.edgeAntialiasingMask = kCALayerTopEdge | kCALayerBottomEdge | kCALayerRightEdge | kCALayerLeftEdge;
[window.contentView addSubview:view];
//window.contentView = view;
NSTextField *label = [[NSTextField alloc] initWithFrame:view.bounds];
[label setBezeled:NO];
[label setDrawsBackground:NO];
[label setEditable:NO];
[label setSelectable:NO];
label.stringValue = text;
label.alignment = NSTextAlignmentCenter;
label.textColor = [NSColor whiteColor];
label.backgroundColor = [NSColor clearColor];
label.font = [NSFont fontWithName:#"Arial-BoldMT" size:fontSize];
//NSRect titleRect = [label titleRectForBounds:view.bounds];
NSSize cellSize = [label.cell cellSizeForBounds:view.bounds];
NSSize strSize = cellSize; // [label.attributedStringValue size];
NSRect frame = view.frame;
frame.origin.y = frame.size.height / 2 - strSize.height / 2;
frame.size.height = strSize.height;
label.frame = frame;
[view addSubview:label];
[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {
context.duration = duration;
window.animator.alphaValue = 0.;
} completionHandler:^{
[window close];
}];
}

Custom UIButton not capturing touches after adding subview

I've got a UIButton declared in interface builder with an outlet set as follows:
#property (weak, nonatomic) IBOutlet UIButton *loginButton;
It works fine until I insert a subview. Then it stops responding. Here's the offending line:
[self.loginButton insertSubview:_gradientButtonView atIndex:0];
Commenting that out makes the button work again. Here's all the code involved (using the awesome SSToolkit and a custom category on UIColor):
SSGradientView *_gradientButtonView = [[SSGradientView alloc] initWithFrame:self.loginButton.layer.bounds];
_gradientButtonView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
_gradientButtonView.topBorderColor = [UIColor colorWithRed:0.558f green:0.599f blue:0.643f alpha:1.0f];
_gradientButtonView.topInsetColor = [UIColor colorWithWhite:1.0f alpha:0.3f];
_gradientButtonView.colors = [NSArray arrayWithObjects:[UIColor from_hex:#"E6E7E8"], [UIColor from_hex:#"A7A9AC"], nil];
_gradientButtonView.layer.cornerRadius = 5;
self.loginButton.layer.cornerRadius = 5;
self.loginButton.titleLabel.shadowOffset = CGSizeMake(0, 1);
[self.loginButton setTitleShadowColor:[UIColor whiteColor] forState:UIControlStateNormal];
self.loginButton.layer.masksToBounds = YES;
_gradientView.bottomBorderColor = [UIColor colorWithRed:0.428f green:0.479f blue:0.520f alpha:1.0f];
_gradientButtonView.clipsToBounds = YES;
_gradientButtonView.userInteractionEnabled = YES;
[self.loginButton insertSubview:_gradientButtonView atIndex:0];
self.loginButton.userInteractionEnabled = YES;
This was answered in the comments above:
Is there a specific reason you're writing
_gradientButtonView.userInteractionEnabled = YES;? To my knowledge, this prevents the view from sending touch events up the responder
chain

UISlider in UIToolbar -> can't get slider.value and process it. iOS SDK

I'm trying to get a UISlider into my UIToolbar and to take the value from it and process it. I also want to be able to change the slider.value via other methods.
So, I set it up for the UISlider by it's self (not on a UIToolBar) and everything worked fine. Then, when I put it into the UIToolBar, the value stopped getting sent to and from it (I am NSLogging it whenever it changes and I keep getting 0 returned to me).
Here's the relevant section of my code - does anybody have any ideas?
- (void)setupToolBarAndSlider {
CGRect frame = CGRectMake(0.0, 0.0, 200.0, 30.0);
UISlider *slider = [[UISlider alloc] initWithFrame:frame];
[slider addTarget:self action:#selector(sliderValueChanged) forControlEvents:UIControlEventValueChanged];
[slider setBackgroundColor:[UIColor clearColor]];
slider.minimumValue = 0;
slider.maximumValue = 8;
slider.continuous = YES;
slider.value = questionNumberForArray;
//Change slider for UIToolbar
UIBarButtonItem *skipQuestionSlider = [[UIBarButtonItem alloc] initWithCustomView:slider];
// Set the width of aSlider
[skipQuestionSlider setWidth:400.0];
//Set up UIToolBar with Slider in it.
UIToolbar *toolBar;
CGRect rect2 = CGRectMake(0, toolBar.frame.origin.y , self.view.frame.size.width , 44);
toolBar = [[UIToolbar alloc]initWithFrame:rect2];
toolBar.barStyle = UIBarStyleBlackTranslucent;
[toolBar setItems:[NSArray arrayWithObjects:skipQuestionSlider, nil]];
[self.view addSubview:toolBar];
}
- (void)sliderValueChanged {
NSInteger roundedSliderNumber = round(skipQuestionSlider.value);
NSLog(#"Slider Value = %d", roundedSliderNumber);
}
Sam
A UIBarButtonItem (in your case, skipQuestionSlider) does not have a value property, it just houses the item. You need to reference the item you put in the UIBarButtonItem.
NSInteger roundedSliderNumber = round(slider.value);

UINavigationController rightbarbuttonitem not showing

after going through the questions related to UINavigationController item i came to post my exact problem ..
firstly i am not add a UINavigationController in MainWindow.xib i created and adding UINavigationController in AppDelegate file
after that in a UIViewController (not in rootViewController) class I have to add a rightbarbutton of Done type I am
adding it in a searchbarDelegate Method showing as bold:-
- (void) searchBarTextDidBeginEditing:(UISearchBar *)theSearchBar {
//This method is called again when the user clicks back from teh detail view.
//So the overlay is displayed on the results, which is something we do not want to happen.
if(exhibDataObj.searching)
return;
//Add the overlay view.
if(ovController == nil)
ovController = [[OverlayViewController alloc] initWithNibName:#"OverlayView" bundle:[NSBundle mainBundle]];
CGFloat yaxis = self.navigationController.navigationBar.frame.size.height;
CGFloat width = self.view.frame.size.width;
CGFloat height = self.view.frame.size.height;
//Parameters x = origion on x-axis, y = origon on y-axis.
CGRect frame = CGRectMake(0, yaxis, width, height);
ovController.view.frame = frame;
ovController.view.backgroundColor = [UIColor grayColor];
ovController.view.alpha = 0.5;
ovController.rvController = self;
[self.theTableView insertSubview:ovController.view aboveSubview:self.parentViewController.view];
exhibDataObj.searching = true;
letUserSelectRow = NO;
self.theTableView.scrollEnabled = NO;
//Add the done button.
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self action:#selector(doneSearching_Clicked:)];
}
but this never works .
Any help will be more appreciable.
I've tested your code real quick and it seems to be working fine for me, however, I've had the same problem once back then it turned out I was setting the rightBarButtonItem to nil in my viewDidLoad method after setting it to a button. you should make sure your not making the same mistake somehow.
However if that does not work for you you can always try setting a custom button to it:
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 5, 30, 30)];
button.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"done.png"]];
[button addTarget:self action:#selector(doneButtonClicked) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationController.visibleViewController.navigationItem.rightBarButtonItem = customItem;

UITextField Delegate Method and Cocos2d?

When I resign the first responder (UITextField-*nameField) via a background tap method, it is not calling the delegate Method. I am using UIKit with cocos2d. Any help is appreciated. Thank you!
Here is the code with the init Method:
CGRect frame = CGRectMake(115, 423,200, 32);
nameField = [[UITextField alloc] initWithFrame:frame];
nameField.borderStyle = UITextBorderStyleNone;
nameField.textColor = [UIColor blackColor];
nameField.textAlignment = UITextAlignmentLeft;
nameField.font = [UIFont fontWithName:#"MarkerFelt-Thin" size:24];
nameField.placeholder = #"Name";
nameField.backgroundColor = [UIColor clearColor];
nameField.autocorrectionType = UITextAutocorrectionTypeNo;
nameField.delegate = self;
nameField.keyboardType = UIKeyboardTypeDefault;
nameField.returnKeyType = UIReturnKeyDone;
[nameField isFirstResponder];
nameField.transform = CGAffineTransformMakeRotation(M_PI / 2.0);
[[[[CCDirector sharedDirector] openGLView] window] addSubview:nameField];
And here is the Delegate Method I am calling. I am also conforming to the delegate protocol within the header file.
-(void)textViewDidEndEditing:(UITextView *)textView{
NSLog(#"Name has been saved in NSUserDefauts");
NSUserDefaults *usrDef = [NSUserDefaults standardUserDefaults];
NSString *name = [[NSString alloc]initWithFormat:#"%#",nameField.text];
NSLog(#"%#",nameField.text);
[usrDef setObject:name forKey:#"Name"];
}
I think you have the wrong delegate method. The one I think you want is this:
- (void)textFieldDidEndEditing:(UITextField *)textField