Show UIAlertController over keyboard - keyboard

In iOS 8 and lower show a UIActionSheet when keyboard is presented will present the action sheet over the keyboard. With iOS 9 this is no longer the case.
In my app we have a chat functionality and want the show a action over the keyboard. We used to use UIActionSheet which worked fine until iOS 8. In iOS 9 the action sheet is present behind the keyboard. I've tried both UIActionSheet and UIAlertController.
What we want is a action sheet like in messages.app
I've tried placing the action sheet in it own window and overriding canBecomeFirstResponder which just made the keyboard disappear.

I have implemented exactly this in our app. The trick is to have the alert controller appear on a different window. This is how the UIActionSheet implementation does it, and works great on iOS 8, but on 9, Apple has moved the keyboard implementation to a window which has a very high window level (10000000). The fix is to give your alert window an even higher window level (as a custom double value, not using the provided constants).
When using a custom window which will have transparency, make sure to read my answer here, regarding background color, to prevent window becoming black during rotation transitions.
_alertWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
_alertWindow.rootViewController = [UIViewController new];
_alertWindow.windowLevel = 10000001;
_alertWindow.hidden = NO;
_alertWindow.tintColor = [[UIWindow valueForKey:#"keyWindow"] tintColor];
__weak __typeof(self) weakSelf = self;
UIAlertController* alert = [UIAlertController alertControllerWithTitle:#"Test" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
[alert addAction:[UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
weakSelf.alertWindow.hidden = YES;
weakSelf.alertWindow = nil;
}]];
[alert addAction:[UIAlertAction actionWithTitle:#"Test" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
weakSelf.alertWindow.hidden = YES;
weakSelf.alertWindow = nil;
}]];
[_alertWindow.rootViewController presentViewController:alert animated:YES completion:nil];

The answer supplied by Leo is broken as of iOS 11, because Apple now prevents you from setting a windowLevel above 10000000. A fix is to implement a custom UIWindow and override the windowLevel receiver:
#interface TopWindow : UIWindow #end
#implementation TopWindow
- (UIWindowLevel) windowLevel {
return 20000000.000;
}
#end
// usage:
UIWindow* w = [[TopWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
w.rootViewController = [UIViewController new];
w.hidden = NO;
[w.rootViewController presentViewController:yourActionSheetController animated:YES completion:nil];
This approach should be backwards compatible, but haven't tested all known versions. Happy hacking!

Based on Leo Natan's answer, I've created a Swift extension for presenting an alert sheet over the keyboard.
In my brief testing, the alertWindow is deallocated after the alert is dismissed, I believe because there's no strong reference to it outside of the alert. This means there's no need to hide or deallocate it in your UIAlertActions.
extension UIAlertController {
func presentOverKeyboard(animated: Bool, completion: (() -> Void)?) {
let alertWindow = UIWindow(frame: UIScreen.mainScreen().bounds)
// If you need a white/hidden/other status bar, use an appropriate VC.
// You may not need a custom class, and you can just use UIViewController()
alertWindow.rootViewController = whiteStatusBarVC()
alertWindow.windowLevel = 10000001
alertWindow.hidden = false
// Set to a tint if you'd like
alertWindow.tintColor = UIColor.greenColor()
alertWindow.rootViewController?.presentViewController(self, animated: animated, completion: completion)
}
}
private class whiteStatusBarVC: UIViewController {
private override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
}

use UIAlertController instead of UIActionSheet

Related

iOS 9 UINavigation bar content is not centred after rotation in iOS 9?

I noticed a bug in iOS 9, or may be I am not using something correctly.
In the following code in an empty project targeted for iPhone :
UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:#"Show" style:UIBarButtonItemStylePlain target:self action:#selector(test:)];
self.navigationItem.rightBarButtonItem = anotherButton;
self.navBar.items = #[self.navigationItem];
I added a custom button to a navigation bar property. I noticed that after rotation from portrait to landscape, the button moves down and it is not centered correctly in the navigation bar.
Portrait Screen
Landscape Screen
This code works fine if I compile for iOS 8.4 for example, but not on iOS 9.
Has anyone encountered this?
Thanks!
I've seen something similar on the iPad. When I start the app in portrait, then rotate to landscape, the View Controller its navigationItem.titleView doesn't align correctly anymore. I simply reset it after rotation as follows in Swift:
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animateAlongsideTransition(nil) { (coordinator) -> Void in
self.navigationItem.titleView = someView
}
}
Swift 3:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animate(alongsideTransition: nil) { (coordinator) -> Void in
self.navigationItem.titleView = self.someView
}
}
I have managed to fix the problem with custom navigation bar class with and overridden method:
-(void) layoutSubviews
{
[super layoutSubviews];
for (UIView *view in self.subviews)
{
if ([view isKindOfClass:[UIView class]] ||
[view isKindOfClass:[UIButton class]] ||
[view isKindOfClass:[UISearchBar class]] ||
[view isKindOfClass:[UILabel class]])
{
CGRect frame = view.frame;
frame.origin.y = (self.frame.size.height - frame.size.height) / 2.f;
view.frame = frame;
}
}
}
Other type of view classes can be added in the if statement. Its not the cleanest solution, but it will do for now.

Cancel button in searchBar ios 8

tell me how to change the text on the Cancel button in searchBar?
Image: http://i.stack.imgur.com/8G1ZM.png
you can do that in this delegate method of UISearchBar
- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
[theSearchBar setShowsCancelButton:YES animated:NO];
for (UIView *subView in theSearchBar.subviews){
if([subView isKindOfClass:[UIButton class]]){
[(UIButton*)subViewsetTitle:#"Button Title"forState:UIControlStateNormal];
}
}
}
UPDATE
after a long way searching the only way i got working in swift
is to set a custom UIBarButtonItem but you will need to show the search bar on the navigation
in ViewDidLoad()
self.searchDisplayController?.displaysSearchBarInNavigationBar = true
and in Delegate Method
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
var barButton = UIBarButtonItem(title: "Button Title", style: UIBarButtonItemStyle.Done, target: self, action: "here")
self.searchDisplayController?.navigationItem.rightBarButtonItem = barButton
}
i hope that works with you
«Another UPDATE
as you said in comments you will need to localize your application, in your case you will only need to localize the storyBoard
first navigate to your project settings then info, under localizations click the + button and add your own languages then check only StoryBoard
and now you have localized your app but you might don't see the changes until you remove the app and install it again or if the device language is set to english you will need to write 2 lines of code to change the language manually here is it
var str:NSString = "ar" // ar stands for arabic you put here you own language small character
var myArray:NSArray = [str]
NSUserDefaults.standardUserDefaults().setObject(myArray, forKey: "AppleLanguages")
and your button will looks like this
if you want to know more about localization see this Internationalization Tutorial for iOS [2014 Edition]
if you still need help till me :)
There are 2 solutions.
set key/value
[self.searchController.searchBar setValue:#"취소" forKey:#"_cancelButtonText"];
This solution works well, but you have to know that _cancelButtonText property is not public property.(You can not find this property in the documentation page.)
And It's not sure that this solution can pass the apple review process. So, use solution 2 please.
use a delegate.
You can change cancel button title(iOS8) within willPresentSearchController method.
(Assume that the searchBar is in tableView headerView)
- (void)willPresentSearchController:(UISearchController *)searchController{
// You have to set YES showsCancelButton.
// If not, you can not change your button title when this method called
// first time.
self.searchController.searchBar.showsCancelButton = YES;
UIView* view=self.searchController.searchBar.subviews[0];
for (UIView *subView in view.subviews) {
if ([subView isKindOfClass:[UIButton class]]) {
// solution 1
UIButton *cancelButton = (UIButton*)subView;
[cancelButton setTitle:NSLocalizedString(#"취소", nil) forState:UIControlStateNormal];
}
}
}
Also, You can get infomation about the searchBar through a view debugging tools in Xcode. Set a breakPoint at the willPresentSearchController method.
Good luck.
Actually, the cancel button is not a top view in the Search bar. You should search for it recursively.
-(UIButton*)findButtonInView:(UIView*)v{
for (UIView *subView in v.subviews){
if([subView isKindOfClass:[UIButton class]]){
return (UIButton*)subView;
}else if([subView isKindOfClass:[UIView class]]){
UIButton* btn = [self findButtonInView:subView];
if(btn){
return btn;
}
}
}
return nil;
}
//...
UIButton* searchButton = [self findButtonInView:self.searchBar];

How do we avoid crashes in async calls that reference cocos2d-iphone (2.0.0) UI classes?

In my iOS game with cocos2d-iphone 2.0.0, I have a layer that pops up a sprite that asks the user to buy an in app purchase with a button for the user to click to buy (menuItemBuyButton). When user clicks on this buy button, three things are done:
an activity indicator is started
all menu items on the layer are disabled - particularly, the main menu (this code is on the main menu scene), the buy button itself and the popup's menu
the usual sequence of purchase calls and callbacks are triggered.
When the purchase is completed, the callback (which is on another thread) then needs to:
stop the activity indicator
reenable the disabled menu elements
replace the scene with another director
Now, when I run this sequence, and test by clicking on the buy button repeatedly, etc., just once (and unable to repro ever again) I got a crash in the code - the code and crash logs are below. I suspect (and may be wrong) this is due to the un-thread-safe nature of cocos2d. How do I avoid this crash? I do need to disable the UI elements before starting the buy transaction and have to reenable them once the transaction is finished, which will happen in another thread.
Code is as below:
-(void) startActivityIndicator {
mainMenu.enabled = NO;
scorePopupMenu.enabled = NO;
menuItemBuyButton.isEnabled = NO;
[activityIndicatorView startAnimating];
}
-(void) stopActivityIndicator {
mainMenu.enabled = YES;
scorePopupMenu.enabled = YES;//this is line 744 that crashed
menuItemBuyButton.isEnabled = YES;
if (activityIndicatorView.isAnimating)
[activityIndicatorView stopAnimating];
}
Crash logs:
5 SmartRun 0x00126c4c -[MainMenuLayer stopActivityIndicator] (MainMenuLayer.m:744)
Then disable repeated tap. Just disable touch once it is pressed and reenable once it is processed.
node.touchEnabled = NO; //do this for all menu and layer
(In Cocos2d 1.0 isTouchEnabled to NO)
We also used inAp purchase in cocos2d game with activity indicator from UIKit. What we did is used activity indicator inside Alert view. That blocks user to do other UI switch.
-(void)ShowActivityIndicator
{
if(!mLoadingView) // UIAlertView *mLoadingView;
{
mLoadingView = [[UIAlertView alloc] initWithTitle:#"" message:#"" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
UIActivityIndicatorView *actInd = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
actInd.frame = CGRectMake(128.0f, 45.0f, 25.0f, 25.0f);
[mLoadingView addSubview:actInd];
[actInd startAnimating];
[actInd release];
UILabel *l = [[UILabel alloc]init];
l.frame = CGRectMake(100, -25, 210, 100);
l.text = #"Please wait...";
l.font = [UIFont fontWithName:#"Helvetica" size:16];
l.textColor = [UIColor whiteColor];
l.shadowColor = [UIColor blackColor];
l.shadowOffset = CGSizeMake(1.0, 1.0);
l.backgroundColor = [UIColor clearColor];
[mLoadingView addSubview:l];
[l release];
}
[mLoadingView show];
}
-(void)StopIndicator
{
[mLoadingView dismissWithClickedButtonIndex:0 animated:NO];
}

Change Navigation Bar Tint Color while presenting new view controller modally in iOS 4.x

In my view controller's I have following code
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSLog(#"%s",__PRETTY_FUNCTION__);
self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:201.0/255.0 green:201.0/255.0 blue:201.0/255.0 alpha:1.0];
}
On this view when I click a button , I am presenting MFMailComposeViewController modally. When I present MFMailComposeViewController modally, navigation bar same color as set in viewWillAppear. I want default blue color as Apple told that don't customize this view. Here is my code which I have tried
Code 1:
-(void)sendEmailWithWithRecipients:(NSArray*)recipients andData:(NSData*)data {
if ([MFMailComposeViewController canSendMail]){
MFMailComposeViewController *mailComposeViewController = [[MFMailComposeViewController alloc] init];
mailComposeViewController.mailComposeDelegate = self;
self.navigationController.navigationBar.tintColor = nil;
[self presentModalViewController:mailComposeViewController animated:YES];
[mailComposeViewController release];
}
else {
[self showAlertWithTitle:#"Alert" andMessage:#"Can not send email. Please check your email settings."];
}
}
But above code is not working for tint color
Code 2: Set tint color in viewWillDisappear
-(void)viewWillDisappear:(BOOL)animated {
NSLog(#"%s",__PRETTY_FUNCTION__);
self.navigationController.navigationBar.tintColor = nil;
[super viewWillDisappear:animated];
}
Code 2 also not working.
But this is working fine in iOS5 without setting tintColor = nil while presenting MFMailComposeViewController modally & in viewWillDisappear. Its not working iOS 4.x
Anyone have solution for this? Thanks.
You can customize the navigationbar's tint color by accessing yourController's(ViewController which you are presetnting) topViewController.
Ex :
[self presentModalViewController:yourController animated:YES];
yourController.topViewController.navigationController.navigationBar.tintColor =
[UIColor (Your Color)];
Try setting the navigation bar style rather than the tint color. Tint color and bar style have slightly different side effects, so while I don't completely understand your needs, it might be exactly what you're looking for.
[self.navigationController.navigationBar setBarStyle:UIBarStyleDefault];
or
self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
And make sure you do this within the context of the modal view controller, not the previous view controller.
Instead of nil try this [UIColor ClearColor];

UISearchBar disable auto disable of cancel button

I have implemented a UISearchBar into a table view and almost everything is working except one small thing: When I enter text and then press the search button on the keyboard, the keyboard goes away, the search results are the only items shown in the table, the text stays in the UISearchBar, but the cancel button gets disabled.
I have been trying to get my list as close to the functionality of the Apple contacts app and when you press search in that app, it doesn't disable the cancel button.
When I looked in the UISearchBar header file, I noticed a flag for autoDisableCancelButton under the _searchBarFlags struct but it is private.
Is there something that I am missing when I setup the UISearchBar?
I found a solution. You can use this for-loop to loop over the subviews of the search bar and enable it when the search button is pressed on the keyboard.
for (UIView *possibleButton in searchBar.subviews)
{
if ([possibleButton isKindOfClass:[UIButton class]])
{
UIButton *cancelButton = (UIButton*)possibleButton;
cancelButton.enabled = YES;
break;
}
}
I had to tweak this a bit to get it work for me in iOS7
- (void)enableCancelButton:(UISearchBar *)searchBar
{
for (UIView *view in searchBar.subviews)
{
for (id subview in view.subviews)
{
if ( [subview isKindOfClass:[UIButton class]] )
{
[subview setEnabled:YES];
NSLog(#"enableCancelButton");
return;
}
}
}
}
There is two way to achieve this easily
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
// The small and dirty
[(UIButton*)[searchBar valueForKey:#"_cancelButton"] setEnabled:YES];
// The long and safe
UIButton *cancelButton = [searchBar valueForKey:#"_cancelButton"];
if ([cancelButton respondsToSelector:#selector(setEnabled:)]) {
cancelButton.enabled = YES;
}
}
You should go with the second one, it will not crash your application if Apple will change it in the background.
BTW i tested it from iOS 4.0 to 8.2 and no changes, also i use it in my Store approved application without any issues.
This is what made it to work on iOS 6 for me:
searchBar.showsCancelButton = YES;
searchBar.showsScopeBar = YES;
[searchBar sizeToFit];
[searchBar setShowsCancelButton:YES animated:YES];
Here's my solution, which works for all situations in all versions of iOS.
IE, other solutions don't handle when the keyboard gets dismissed because the user dragged a scroll view.
- (void)enableCancelButton:(UIView *)view {
if ([view isKindOfClass:[UIButton class]]) {
[(UIButton *)view setEnabled:YES];
} else {
for (UIView *subview in view.subviews) {
[self enableCancelButton:subview];
}
}
}
// This will handle whenever the text field is resigned non-programatically
// (IE, because it's set to resign when the scroll view is dragged in your storyboard.)
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
[self performSelector:#selector(enableCancelButton:) withObject:searchBar afterDelay:0.001];
}
// Also follow up every [searchBar resignFirstResponder];
// with [self enableCancelButton:searchBar];
As per my answer here, place this in your searchBar delegate:
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
dispatch_async(dispatch_get_main_queue(), ^{
__block __weak void (^weakEnsureCancelButtonRemainsEnabled)(UIView *);
void (^ensureCancelButtonRemainsEnabled)(UIView *);
weakEnsureCancelButtonRemainsEnabled = ensureCancelButtonRemainsEnabled = ^(UIView *view) {
for (UIView *subview in view.subviews) {
if ([subview isKindOfClass:[UIControl class]]) {
[(UIControl *)subview setEnabled:YES];
}
weakEnsureCancelButtonRemainsEnabled(subview);
}
};
ensureCancelButtonRemainsEnabled(searchBar);
});
}
None of the answers worked for me at all. I'm targeting iOS 7. But I found an answer.
What I'm trying is something like the Twitter iOS app. If you click on the magnifying glass in the Timelines tab, the UISearchBar appears with the Cancel button activated, the keyboard showing, and the recent searches screen. Scroll the recent searches screen and it hides the keyboard but it keeps the Cancel button activated.
This is my working code:
UIView *searchBarSubview = self.searchBar.subviews[0];
NSArray *subviewCache = [searchBarSubview valueForKeyPath:#"subviewCache"];
if ([subviewCache[2] respondsToSelector:#selector(setEnabled:)]) {
[subviewCache[2] setValue:#YES forKeyPath:#"enabled"];
}
I arrived at this solution by setting a breakpoint at my table view's scrollViewWillBeginDragging:. I looked into my UISearchBar and bared its subviews. It always has just one, which is of type UIView (my variable searchBarSubview).
Then, that UIView holds an NSArray called subviewCache and I noticed that the last element, which is the third, is of type UINavigationButton, not in the public API. So I set out to use key-value coding instead. I checked if the UINavigationButton responds to setEnabled:, and luckily, it does. So I set the property to #YES. Turns out that that UINavigationButton is the Cancel button.
This is bound to break if Apple decides to change the implementation of a UISearchBar's innards, but what the hell. It works for now.
Here's a Swift 3 solution that makes use of extensions to get the cancel button easily:
extension UISearchBar {
var cancelButton: UIButton? {
for subView1 in subviews {
for subView2 in subView1.subviews {
if let cancelButton = subView2 as? UIButton {
return cancelButton
}
}
}
return nil
}
}
Now for the usage:
class MyTableViewController : UITableViewController, UISearchBarDelegate {
var searchBar = UISearchBar()
func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
tableView.tableHeaderView = searchBar
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
DispatchQueue.main.async {
if let cancelButton = searchBar.cancelButton {
cancelButton.isEnabled = true
cancelButton.isUserInteractionEnabled = true
}
}
}
}
For Monotouch or Xamarin iOS I have the following C# solution working for iOS 7 and iOS 8:
foreach(UIView view in searchBar.Subviews)
{
foreach(var subview in view.Subviews)
{
//Console.WriteLine(subview.GetType());
if(subview.GetType() == typeof(UIButton))
{
if(subview.RespondsToSelector(new Selector("setEnabled:")))
{
UIButton cancelButton = (UIButton)subview;
cancelButton.Enabled = true;
Console.WriteLine("enabledCancelButton");
return;
}
}
}
}
This answer is based on David Douglas solution.
A more complete answer:
since iOS 7, there is an additional level of subviews under the searchBar
a good place to enable the cancel button is in searchBarTextDidEndEditing
.
extension MyController: UISearchBarDelegate {
public func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
DispatchQueue.main.async {
// you need that since the disabling will
// happen after searchBarTextDidEndEditing is called
searchBar.subviews.forEach({ view in
view.subviews.forEach({ subview in
// ios 7+
if let cancelButton = subview as? UIButton {
cancelButton.isEnabled = true
cancelButton.isUserInteractionEnabled = true
return
}
})
// ios 7-
if let cancelButton = subview as? UIButton {
cancelButton.isEnabled = true
cancelButton.isUserInteractionEnabled = true
return
}
})
}
}
}
Time passes, but the problem is still there...
Elegant Swift 5/iOS 13 solution:
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
for case let cancelButton as UIButton in searchBar.subviews {
cancelButton.isEnabled = true
}
}

Resources