Is there a way to prevent the keyboard from dismissing? - iphone

I realize that this is the inverse of most posts, but I would like for the keyboard to remain up even if the 'keyboard down' button is pressed.
Specifically, I have a view with two UITextFields. With the following delegate method
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
return NO;
}
I am able to keep the keyboard up even if the user presses the Done button on the keyboard or taps anywhere else on the screen EXCEPT for that pesky keyboard down button on the bottom right of the keyboard.
I am using this view like a modal view (though the view is associated with a ViewController that gets pushed in a UINavigationController), so it really works best from a user perspective to keep the keyboard up all of the time. If anyone knows how to achieve this, please let me know! Thanks!
UPDATE Still no solution! When Done is pressed, it triggers textFieldShouldReturn, but when the Dismiss button is pressed, it triggers textFieldDidEndEditing. I cannot block the textField from ending editing or it never goes away. Somehow, I really want to have a method that detects the Dismiss button and ignores it. If you know a way, please enlighten me!

There IS a way to do this. Because UIKeyboard subclasses UIWindow, the only thing big enough to get in UIKeyboard's way is another UIWindow.
- (void)viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(coverKey) name:UIKeyboardDidShowNotification object:nil];
[super viewDidLoad];
}
- (void)coverKey {
CGRect r = [[UIScreen mainScreen] bounds];
UIWindow *myWindow = [[UIWindow alloc] initWithFrame:CGRectMake(r.size.width - 50 , r.size.height - 50, 50, 50)];
[myWindow setBackgroundColor:[UIColor clearColor]];
[super.view addSubview:myWindow];
[myWindow makeKeyAndVisible];
}
This works on iPhone apps. Haven't tried it with iPad. You may need to adjust the size of myWindow. Also, I didn't do any mem management on myWindow. So, consider doing that, too.

I think I've found a good solution.
Add a BOOL as instance variable, let's call it shouldBeginCalledBeforeHand
Then implement the following methods:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
shouldBeginCalledBeforeHand = YES;
return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
return shouldBeginCalledBeforeHand;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
shouldBeginCalledBeforeHand = NO;
}
As well as
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
return NO;
}
to prevent the keyboard from disappearing with the return button. The trick is, a focus switch from one textfield to another will trigger a textFieldShouldBeginEditing beforehand. If the dismiss keyboard button is pressed this doesn't happen. The flag is reset after a textfield has gotten focus.

Old not perfect solution
I can only think of a not perfect solution. Listen for the notification UIKeyboardDidHideNotification and make of the textfields first responder again. This will move the keyboard out of sight and back again. You could keep record of which textfield was the last firstResponder by listening for UIKeyboardWillHideNotification and put focus on it in the didHide.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardDidHide:)
name:UIKeyboardDidHideNotification
object:nil];
...
- (void)keyboardDidHide:(id)sender
{
[myTextField becomeFirstResponder];
}

For iOS 9/10 and Swift 3, use this to create a rect which overlaps the "Hide keyboard" - Button
override func viewDidLoad() {
NotificationCenter.default.addObserver(self, selector: #selector(coverKey), name: .UIKeyboardDidShow, object: nil)
}
func coverKey() {
if let keyboardWindow = UIApplication.shared.windows.last {
let r = UIScreen.main.bounds
let myWindow = UIWindow.init(frame: CGRect(x: r.size.width - 50 , y: r.size.height - 50, width: 50, height: 50))
myWindow.backgroundColor = UIColor.clear
myWindow.isHidden = false
keyboardWindow.addSubview(myWindow)
keyboardWindow.bringSubview(toFront: myWindow)
}
}
Notice that this adds a sub view to the keyboard window instead of the main window

Try adding a custom on top of the keyboard dismiss button so that the user won't be able to tab the dismiss button. I have used this method in one of my application.
- (void)addButtonToKeyboard {
// create custom button
UIButton *blockButton = [UIButton buttonWithType:UIButtonTypeCustom];
blockButton.frame = //set the frame here, I don't remember the exact frame
[blockButton setImage:[UIImage imageNamed:#"block_button.png"] forState:UIControlStateNormal];
// locate keyboard view
UIWindow *appWindows = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
UIView *keyboard;
for (int i=0; i<[appWindows.subviews count]; i++) {
keyboard = [appWindows.subviews objectAtIndex:i];
// keyboard found, add the button
if ([[keyboard description] hasPrefix:#"<UIPeripheralHost"] == YES && [self.textField isFirstResponder]) {
[keyboard addSubview:doneButton];
}
}
}

Try this...
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
return NO;
}
You can use notification as mentioned by Nick Weaver.

Related

Scroll up UITextField on Next

I am creating a "sign in" and "create account" form for my iOS app. I successfully implemented the scrolling up of the UITextField when it is hidden. However, now that I implemented the "next" button the "UIKeyboardDidShowNotification" is not called because the keyboard is never dismissed. I need the keyboardWasShow method called so I can check if the active UITextField is hidden or not.
// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
// If active text field is hidden by keyboard, scroll it so it's visible
// Your application might not need or want this behavior.
CGRect aRect = self.view.frame;
CGPoint pointInSuperview = [self.view convertPoint:self.activeField.frame.origin fromView:self.scrollView];
aRect.size.height -= kbSize.height;
//added 10 to y axis because tip of origin was outside of keyboard
pointInSuperview.y +=20;
if (!CGRectContainsPoint(aRect, pointInSuperview)) {
CGPoint scrollPoint = CGPointMake(0.0, pointInSuperview.y - (kbSize.height -15));
NSLog(#"it is not in the rect");
[self.scrollView setContentOffset:scrollPoint animated:YES];
}
}
and I have an observer
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
and after I implemented my Next button (see below) the keyboardWasShown method is not called so it never checks if the active UITextField is hidden.
//functionality for next action
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if (textField == self.emailAddress) {
[self.fullName becomeFirstResponder];
[self keyboardWasShown:(NSNotification*)UIKeyboardDidShowNotification];
}
else if (textField == self.fullName) {
[self.password becomeFirstResponder];
}
else if (textField == self.password) {
[self.confirmPassword becomeFirstResponder];
}
[textField resignFirstResponder];
return YES;
}
What would be the best approach to call keyboardWasShown when the user clicks the Next button? I tried making it a public method but I kept getting errors when I tried to call it manually.
One way to avoid this is to resign the responder prior to setting the next responder, which will ensure that the keyboardWasShown notification was called. For example, based on your code you could use the following:
...
else if (textField == self.fullName) {
[self.fullName resignFirstResponder];
[self.password becomeFirstResponder];
}
...
Whilst this might seem odd, it should be noted that the keyboard doesn't actually disappear/reappear.
You may want to look into this
If your fields arent in a table the same sort of logic can apply to other cases.

How to set cursor position for UITextView on user input?

I am looking for a simple answer for this problem...
I have a UITextView in which the user can start typing and click on DONE and resign the keyboard.
When the wants to edit it again, I want the cursor (the blinking line) to be at the first position of the textView, not at the end of textView. (act like a placeholder)
I tried setSelectedRange with NSMakeRange(0,0) on textViewDidBeginEditing, but it does not work.
More Info:
It can be seen that.. when the user taps on the textView the cursor comes up at the position where the user taps on the textView.
I want it to always blink at starting position when textViewDidBeginEditing.
The property selectedRange can not be assigned at "any place", to make it work you have to implement the method - (void)textViewDidChangeSelection:(UITextView *)textView, in your case:
- (void)textViewDidChangeSelection:(UITextView *)textView
{
[textView setSelectedRange:NSMakeRange(0, 0)];
}
you will have to detect when the user is beginning editing or selecting text
My solution:
- (void) viewDidLoad {
UITextView *textView = [[UITextView alloc] initWithFrame: CGRectMake(0, 0, 200, 200)];
textView.text = #"This is a test";
[self.view addSubview: textView];
textView.delegate = self;
[textView release];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget: self action: #selector(tapped:)];
[textView addGestureRecognizer: tap];
[tap release];
}
- (void) tapped: (UITapGestureRecognizer *) tap {
[textView becomeFirstResponder];
}
- (void) textViewDidBeginEditing:(UITextView *)textView {
textView.selectedRange = NSMakeRange(0, 0);
}
I guess it's UITextView internal mechanism to set the cursor when user taps on it. We need to override that by attaching a tap gesture recognizer and call becomeFirstResponder instead.
I was facing the same issue - basically there's a delay when becoming first responder that doesn't allow you to change selectedRange in any of textView*BeginEditing: methods. If you try to delay the setSelectedRange: (let's say with performSelector:withObject:afterDelay:) it shows ugly jerk.
The solution is actually pretty simple - checking order of delegate methods gives you the hint:
textViewShouldBeginEditing:
textViewDidBeginEditing:
textViewDidChangeSelection:
Setting selectedRange in the last method (3) does the trick, you just need to make sure you reposition the cursor only for the first time when the UITextView becomes first responder as the method (3) is called every time you update the content.
A BOOL variable set in shouldChangeTextInRange: one of the methods (1), (2) and check for the variable in (3) should do the trick ... just don't forget to reset the variable after the reposition to avoid constant cursor reset :).
Hope it helps!
EDIT
After few rounds of testing I decided to set the BOOL flag in shouldChangeTextInRange: instead of (2) or (3) as it proved to be more versatile. See my code:
#interface MyClass
{
/** A flag to determine whether caret should be positioned (YES - don't position caret; NO - move caret to beginning). */
BOOL _isContentGenerated;
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
// deleting
if([text length] == 0)
{
// deleting last character
if(range.length == [[textView text] length])
{
// reached beginning
/**
code to show placeholder and reset caret to the beginning
*/
_isContentGenerated = NO;
}
}
else
{
// adding
if(range.location == 0)
{
/**
code to hide placeholder
*/
_isContentGenerated = YES;
}
}
return YES;
}
- (void)textViewDidChangeSelection:(UITextView *)textView
{
if(!_isContentGenerated)
{
[textView setSelectedRange:NSMakeRange(0, 0)];
}
}
I haven't worked enough with that to help you fully, but what happens when you try to play with different selectedRanges? Say, if you do [... setSelectedRange:[NSMakeRange(0,1)]] or [... setSelectedRange:[NSMakeRange(1,0)]]? Does it move the cursor anywhere?
So I ended up adding a UILabel over the UITextView which acts as a placeholder for the textView. Tapping on the UILabel would send the action down to the textView and becomeFirstResponder. Once you start typing, make the label hidden.
[_detailAreaView setTextContainerInset:UIEdgeInsetsMake(8, 11, 8, 11)];

iOS: How to access the `UIKeyboard`?

I want to get a pointer reference to UIKeyboard *keyboard to the keyboard on screen so that I can add a transparent subview to it, covering it completely, to achieve the effect of disabling the UIKeyboard without hiding it.
In doing this, can I assume that there's only one UIKeyboard on the screen at a time? I.e., is it a singleton? Where's the method [UIKeyboard sharedInstance]. Brownie points if you implement that method via a category. Or, even more brownie points if you convince me why it's a bad idea to assume only one keyboard and give me a better solution.
Try this:
// my func
- (void) findKeyboard {
// Locate non-UIWindow.
UIWindow *keyboardWindow = nil;
for (UIWindow *testWindow in [[UIApplication sharedApplication] windows]) {
if (![[testWindow class] isEqual:[UIWindow class]]) {
keyboardWindow = testWindow;
break;
}
}
// Locate UIKeyboard.
UIView *foundKeyboard = nil;
for (UIView *possibleKeyboard in [keyboardWindow subviews]) {
// iOS 4 sticks the UIKeyboard inside a UIPeripheralHostView.
if ([[possibleKeyboard description] hasPrefix:#"<UIPeripheralHostView"]) {
possibleKeyboard = [[possibleKeyboard subviews] objectAtIndex:0];
}
if ([[possibleKeyboard description] hasPrefix:#"<UIKeyboard"]) {
foundKeyboard = possibleKeyboard;
break;
}
}
}
How about using -[UIApplication beginIgnoringInteractionEvents]?
Also, another trick to get the view containing the keyboard is to initialize a dummy view with CGRectZero and set it as the inputAccessoryView of your UITextField or UITextView. Then, get its superview. Still, such shenanigans is private/undocumented, but I've heard of apps doing that and getting accepted anyhow. I mean, how else would Instagram be able to make their comment keyboard interactive (dismiss on swipe) like the Messages keyboard?
I found that developerdoug's answer wasn't working on iOS 7, but by modifying things slightly I managed to get access to what I needed. Here's the code I used:
-(UIView*)findKeyboard
{
UIView *keyboard = nil;
for (UIWindow* window in [UIApplication sharedApplication].windows)
{
for (UIView *possibleKeyboard in window.subviews)
{
if ([[possibleKeyboard description] hasPrefix:#"<UIPeripheralHostView"])
{
keyboard = possibleKeyboard;
break;
}
}
}
return keyboard;
}
From what I could make out, in iOS 7 the keyboard is composed of a UIPeripheralHostView containing two subviews: a UIKBInputBackdropView (which provides the blur effect on whatever's underneath the keyboard) and a UIKeyboardAutomatic (which provides the character keys). Manipulating the UIPeripheralHostView seems to be equivalent to manipulating the entire keyboard.
Discaimer: I have no idea whether Apple will accept an app that uses this technique, nor whether it will still work in future SDKs.
Be aware, Apple has made it clear that applications which modify private view hierarchies without explicit approval beforehand will be rejected. Take a look in the Apple Developer Forums for various developers' experience on the issue.
If you're just trying to disable the keyboard (prevent it from receiving touches), you might try adding a transparent UIView that is the full size of the screen for the current orientation. If you add it as a subview of the main window, it might work. Apple hasn't made any public method of disabling the keyboard that I'm aware of - you might want to use one of your support incidents with Apple, maybe they will let you in on the solution.
For an app I am currently developing I am using a really quick and easy method:
Add this in the header file:
// Add in interface
UIWindow * _window;
// Add as property
#property (strong, nonatomic) IBOutlet UIView * _keyboard;
Then add this code in the bottom of the keyboardWillShow function:
-(void) keyboardWillShow: (NSNotification *) notification {
.... // other keyboard will show code //
_window = [UIApplication sharedApplication].windows.lastObject;
[NSTimer scheduledTimerWithTimeInterval:0.05
target:self
selector:#selector(allocateKeyboard)
userInfo:nil
repeats:NO];
}
This code look for when the keyboard is raised and then allocates the current window. I have then added a timer to allocate the keyboard as there were some issues when allocated immediately.
- (void)allocateKeyboard {
if (!_keyboard) {
if (_window.subviews.count) {
// The keyboard is always the 0th subview
_keyboard = _window.subviews[0];
}
}
}
We now have the keyboard allocated which gives you direct "access" to the keyboard as the question asks.
Hope this helps
Under iOS 8 it appears you have to jump down the chain more than in the past. The following works for me to get the keyboard, although with custom keyboards available and such I wouldn't rely on this working unless you're running in a controlled environment.
- (UIView *)findKeyboard {
for (UIWindow* window in [UIApplication sharedApplication].windows) {
UIView *inputSetContainer = [self viewWithPrefix:#"<UIInputSetContainerView" inView:window];
if (inputSetContainer) {
UIView *inputSetHost = [self viewWithPrefix:#"<UIInputSetHostView" inView:inputSetContainer];
if (inputSetHost) {
UIView *kbinputbackdrop = [self viewWithPrefix:#"<_UIKBCompatInput" inView:inputSetHost];
if (kbinputbackdrop) {
UIView *theKeyboard = [self viewWithPrefix:#"<UIKeyboard" inView:kbinputbackdrop];
return theKeyboard;
}
}
}
}
return nil;
}
- (UIView *)viewWithPrefix:(NSString *)prefix inView:(UIView *)view {
for (UIView *subview in view.subviews) {
if ([[subview description] hasPrefix:prefix]) {
return subview;
}
}
return nil;
}

How to disable alertview's button in iPhone?

I have alert view having 2 buttons "OK" and "Cancel" and a textfield.
Now i want to disable "OK" button until user enter some text in textfield.
How can i do this?
thanks in advance
UPDATE 2: For Swift 5.1
<#your alert controller#>.addTextField {(tf) in
//... set your tf characteristics i.e .keyboardType here
NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification,
object: tf,
queue: OperationQueue.main) { _ in
//enable or disable the selected action depending on whether the textField text is empty
<#your alert controller#>.actions[0].isEnabled = !tf.text!.isEmpty
}
}
posting this to update the response since ios 5 :
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
UITextField *textField = [alertView textFieldAtIndex:0];
if ([textField.text length] == 0)
{
return NO;
}
return YES;
}
UPDATE:iOS 8 Since Apple have deprecated the UIAlertView in favour of the UIAlertController. There is no longer a delegate call to alertViewShouldEnableFirstOtherButton:
So instead you would set the buttons enabled property via the UITextFieldTextDidChangeNotification
Add a textView to the alert with
(void)addTextFieldWithConfigurationHandler:(void (^)(UITextField *textField))configurationHandler
[<#your alert#> addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.delegate = self;
textField.tag = 0; //set a tag to 0 though better to use a #define
}];
Then implement the delegate method
(void)textFieldDidBeginEditing:(UITextField *)textField
- (void)textFieldDidBeginEditing:(UITextField *)textField{
//in here we want to listen for the "UITextFieldTextDidChangeNotification"
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(textFieldHasText:)
name:UITextFieldTextDidChangeNotification
object:textField];
}
When the text in textField changes it will invoke a call to "textFieldHasText:" and pass along a NSNotification*
-(void)textFieldHasText:(NSNotification*)notification{
//inside the notification is the object property which is the textField
//we cast the object to a UITextField*
if([[(UITextField*)notification.object text] length] == 0){
//The UIAlertController has actions which are its buttons.
//You can get all the actions "buttons" from the `actions` array
//we have just one so its at index 0
[<#your alert#>.actions[0] setEnabled:NO];
}
else{
[<#your alert#>.actions[0] setEnabled:YES];
}
}
Don't forget to remove your observer when done
I wanted to extend the answer by Ryan Forsyth by adding this. If you add a Default styled UIAlertView, you can get an out of range exception if you try to access a textfield as none exist, so check your view style first.
-(BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView*)alertView
{
if(alertView.alertViewStyle == UIAlertViewStyleLoginAndPasswordInput ||
alertView.alertViewStyle == UIAlertViewStylePlainTextInput ||
alertView.alertViewStyle == UIAlertViewStyleSecureTextInput)
{
NSString* text = [[alertView textFieldAtIndex:0] text];
return ([text length] > 0);
}
else if (alertView.alertViewStyle == UIAlertViewStyleDefault)
return true;
else
return false;
}
You can create two buttons for Ok and Cancel.Then add those two as sub views in the UIAlertView.Now by checking the text(text length) in the textfield,You can perform enable and disable actions.
Without knowing the context of your application, the following may not apply - but have you read the iOS Human Interface Guidelines? It sounds as though you may be better off finding an alternative to UIAlertView if this is something that's going to be displayed to the user often.
Not really related to your question, but do not modify default UIAlertView if you don't want your app to be rejected. If I'm not wrong, you're adding textfields to the alertview, don't you? Like a login view. You should create your own view.
So, regarding your question, create your view, set the buttons has disabled, and delegate the UITextFields. When
- (void)textFieldDidBeginEditing:(UITextField *)textField;
is called, enable those buttons.

How to detect touches in status bar

I have custom view in my application which can be scrolled by the user. This view, however, does not inherit from UIScrollView. Now I want the user to be able to scroll this view to the top, just as any other scrollable view allows. I figured that there is no direct way to do so.
Google turned up one solution: http://cocoawithlove.com/2009/05/intercepting-status-bar-touches-on.html This no longer works on iOS 4.x. That's a no-go.
I had the idea of creating a scrollview and keeping it around somewhere, just to catch it's notifications and then forward them to my control. This is not a nice way to solve my problem, so I am looking for "cleaner" solutions. I like the general approach of the aforementioned link to subclass UIApplication. But what API can give me reliable info?
Are there any thoughts, help, etc...?
Edit: Another thing I don't like about my current solution is that it only works as long as the current view does not have any scroll views. The scroll-to-top gesture works only if exactly one scroll view is around. As soon as the dummy is added (see my answer below for details) to a view with another scrollview, the gesture is completely disabled. Another reason to look for a better solution...
Finally, i've assembled the working solution from answers here. Thank you guys.
Declare notification name somewhere (e.g. AppDelegate.h):
static NSString * const kStatusBarTappedNotification = #"statusBarTappedNotification";
Add following lines to your AppDelegate.m:
#pragma mark - Status bar touch tracking
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
CGPoint location = [[[event allTouches] anyObject] locationInView:[self window]];
CGRect statusBarFrame = [UIApplication sharedApplication].statusBarFrame;
if (CGRectContainsPoint(statusBarFrame, location)) {
[self statusBarTouchedAction];
}
}
- (void)statusBarTouchedAction {
[[NSNotificationCenter defaultCenter] postNotificationName:kStatusBarTappedNotification
object:nil];
}
Observe notification in the needed controller (e.g. in viewWillAppear):
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(statusBarTappedAction:)
name:kStatusBarTappedNotification
object:nil];
Remove observer properly (e.g. in viewDidDisappear):
[[NSNotificationCenter defaultCenter] removeObserver:self name:kStatusBarTappedNotification object:nil];
Implement notification-handling callback:
- (void)statusBarTappedAction:(NSNotification*)notification {
NSLog(#"StatusBar tapped");
//handle StatusBar tap here.
}
Hope it will help.
Swift 3 update
Tested and works on iOS 9+.
Declare notification name somewhere:
let statusBarTappedNotification = Notification(name: Notification.Name(rawValue: "statusBarTappedNotification"))
Track status bar touches and post notification. Add following lines to your AppDelegate.swift:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
let statusBarRect = UIApplication.shared.statusBarFrame
guard let touchPoint = event?.allTouches?.first?.location(in: self.window) else { return }
if statusBarRect.contains(touchPoint) {
NotificationCenter.default.post(statusBarTappedNotification)
}
}
Observe notification where necessary:
NotificationCenter.default.addObserver(forName: statusBarTappedNotification.name, object: .none, queue: .none) { _ in
print("status bar tapped")
}
So this is my current solution, which works amazingly well. But please come with other ideas, as I don't really like it...
Add a scrollview somewhere in your view. Maybe hide it or place it below some other view etc.
Set its contentSize to be larger than the bounds
Set a non-zero contentOffset
In your controller implement a delegate of the scrollview like shown below.
By always returning NO, the scroll view never scrolls up and one gets a notification whenever the user hits the status bar. The problem is, however, that this does not work with a "real" content scroll view around. (see question)
- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView
{
// Do your action here
return NO;
}
Adding this to your AppDelegate.swift will do what you want:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
let events = event!.allTouches()
let touch = events!.first
let location = touch!.locationInView(self.window)
let statusBarFrame = UIApplication.sharedApplication().statusBarFrame
if CGRectContainsPoint(statusBarFrame, location) {
NSNotificationCenter.defaultCenter().postNotificationName("statusBarSelected", object: nil)
}
}
Now you can subscribe to the event where ever you need:
NSNotificationCenter.defaultCenter().addObserverForName("statusBarSelected", object: nil, queue: nil) { event in
// scroll to top of a table view
self.tableView!.setContentOffset(CGPointZero, animated: true)
}
Thanks Max, your solution worked for me after spending ages looking.
For information :
dummyScrollView = [[UIScrollView alloc] init];
dummyScrollView.delegate = self;
[view addSubview:dummyScrollView];
[view sendSubviewToBack:dummyScrollView];
then
dummyScrollView.contentSize = CGSizeMake(view.frame.size.width, view.frame.size.height+200);
// scroll it a bit, otherwise scrollViewShouldScrollToTop not called
dummyScrollView.contentOffset = CGPointMake(0, 1);
//delegate :
- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView
{
// DETECTED! - do what you need to
NSLog(#"scrollViewShouldScrollToTop");
return NO;
}
Note that I had a UIWebView also which I had to hack a bit with a solution I found somewhere :
- (void)webViewDidFinishLoad:(UIWebView *)wv
{
[super webViewDidFinishLoad:wv];
UIScrollView *scroller = (UIScrollView *)[[webView subviews] objectAtIndex:0];
if ([scroller respondsToSelector:#selector(setScrollEnabled:)])
scroller.scrollEnabled = NO;
}
Found a much better solution which is iOS7 compatible here :http://ruiaureliano.tumblr.com/post/37260346960/uitableview-tap-status-bar-to-scroll-up
Add this method to your AppDelegate:
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
CGPoint location = [[[event allTouches] anyObject] locationInView:[self window]];
if (CGRectContainsPoint([UIApplication sharedApplication].statusBarFrame, location)) {
NSLog(#"STATUS BAR TAPPED!");
}
}
I implemented this by adding a clear UIView over the status bar and then intercepting the touch events
First in your Application delegate application:didFinishLaunchingWithOptions: add these 2 lines of code:
self.window.backgroundColor = [UIColor clearColor];
self.window.windowLevel = UIWindowLevelStatusBar+1.f;
Then in the view controller you wish to intercept status bar taps (or in the application delegate) add the following code
UIView* statusBarInterceptView = [[[UIView alloc] initWithFrame:[UIApplication sharedApplication].statusBarFrame] autorelease];
statusBarInterceptView.backgroundColor = [UIColor clearColor];
UITapGestureRecognizer* tapRecognizer = [[[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(statusBarClicked)] autorelease];
[statusBarInterceptView addGestureRecognizer:tapRecognizer];
[[[UIApplication sharedApplication].delegate window] addSubview:statusBarInterceptView];
In the statusBarClicked selector, do what you need to do, in my case I posted a notification to the notification center so that other view controllers can respond to the status bar tap.
Use an invisible UIScrollView. Tested at iOS 10 & Swift 3.
override func viewDidLoad() {
let scrollView = UIScrollView()
scrollView.bounds = view.bounds
scrollView.contentOffset.y = 1
scrollView.contentSize.height = view.bounds.height + 1
scrollView.delegate = self
view.addSubview(scrollView)
}
func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool {
debugPrint("status bar tapped")
return false
}
You can track status bar tap by using following code:
[[NSNotificationCenter defaultCenter] addObserverForName:#"_UIApplicationSystemGestureStateChangedNotification"
object:nil
queue:nil
usingBlock:^(NSNotification *note) {
NSLog(#"Status bar pressed!");
}];
One way, might not be the best, could be to put a clear UIView on top of the status bar and intercept the touches of the UIView, might help you out if nothing else comes up...
If you're just trying to have a UIScrollView scroll to the top when the status bar is tapped, it's worth noting that this is the default behavior IF your view controller has exactly one UIScrollView in its subviews that has scrollsToTop set to YES.
So I just had to go and find any other UIScrollView (or subclasses: UITableView, UICollectionView, and set scrollsToTop to be NO.
To be fair, I found this info in the post that was linked to in the original question, but it's also dismissed as no longer working so I skipped it and only found the relevant piece on a subsequent search.
For iOS 13 this has worked for me, Objective-C category of UIStatusBarManager
#implementation UIStatusBarManager (CAPHandleTapAction)
-(void)handleTapAction:(id)arg1 {
// Your code here
}
#end