Is there an interface to create the glossy cut/copy popup - iphone

Is there a way to create one of the black glossy popups, similar to the one that appears to copy and paste text. I just want to give some information, so the behaviour I want is closer to the way the keyboard popup works when you type a letter but the appearance I want is the copy/paste dialogue.
Are either of these open to the public, or do I have to create my own implementation?

The copy/cut/paste UI is given for free with any of the text based UI controls in UIKit (UITextField, UITextView, etc.), but if you want to use a similary styled UI with other parts of your app you'll have to create your own.

You want to look at UIMenuItemController. The sample project "CopyPasteTile" provides an example of a custom implementation.
Second time this has come up this morning!
Here's some sample code for adding a custom menu item to a UIView subclass (it assumes you've added a long press gesture recognizer with the appropriate target action):
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
if (action == #selector(laughOutLoud:))
return YES;
return NO;
}
- (void)laughOutLoud:(id)sender {
NSLog(#"LOL!");
}
- (void)gestureRecognizerDidPress:(UILongPressGestureRecognizer*)recognizer {
if ([recognizer state] == UIGestureRecognizerStateBegan) {
// Important: the view must become the first responder,
// and implement the canBecomeFirstResponder method.
[self becomeFirstResponder];
UIMenuController *controller = [UIMenuController sharedMenuController];
UIMenuItem *testItem1 = [[UIMenuItem alloc] initWithTitle:#"Laugh" action:#selector(laughOutLoud:)];
[controller setMenuItems:[NSArray arrayWithObject:testItem1]];
[controller update];
// In real life, the target rect should represent the selection
[controller setTargetRect:CGRectZero inView:self];
[controller setMenuVisible:YES animated:YES];
}
}

Related

Entering UIImagePickerController editing mode

I use a UIImagePickerController (photoPicker) to take pictures with the camera, and edit those picture (allowEditing = YES). The user can switch between Camera and Library with a button in photoPicker.view, but I want to remove this button when photoPicker is in editing mode.
In photoLibrarySourceType the picker uses a push to show editing mode, so it works with this method:
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
if (navigationController == photoPicker) {
NSLog(#"navigation ");
if ([navigationController.viewControllers indexOfObject:viewController] == 1)
{
// If second UIViewController, set your overlay.
NSLog(#"editing");
}
}
}
But in cameraSourceType, there is no navigation between camera and editing mode.
I came up with a little hack and it works for me. Am still a little new so please optimize at will as i couldn't find another way to do it.
The basic idea is to create an invisible button over the default camera button that performs a method that calls [uiimagepickercontroller takePicture]
here is my sample code
#implementation myViewController
{
UIImagePickerController *myImagePickerController;
UIButton * fakeCameraButton;
}
- (IBAction)showImagePicker:(id)sender{
// accessible camera validations implied
myImagePickerController = [[UIImagePickerController alloc]init];
myImagePickerController.sourceType=UIImagePickerControllerSourceTypeCamera;
myImagePickerController.showsCameraControls = YES;
myImagePickerController.delegate=self;
myImagePickerController.allowsEditing=YES;
CGFloat myViewHeight = 100; // you play around with the positions to get your desired frame size. This worked for me
UIView * myView = [[UIView alloc] initWithFrame:CGRectMake(0, myImagePickerController.view.frame.size.height - myViewheight, picker.view.frame.size.width, myViewheight)];
fakeCameraButton = [[UIButton alloc] initWithFrame:CGRectMake(myView.frame.size.width / 2 - 30, myView.frame.size.height/2-15, 60, 60)];// position it over the default camera button
[fakeCameraButton addTarget:self action:#selector(cameraButtonPressed) forControlEvents:UIControlEventTouchUpInside];
[fakeCameraButton setTitle:#"" forState:UIControlStateNormal];
[myView addSubview:fakeCameraButton];
myImagePickerController.cameraOverlayView = myView;
[self presentViewController:myImagePickerController animated:YES completion:nil];
}
-(void)cameraButtonPressed{
// Make sure you check if camera is ready before this method.
[myImagePickerController takePicture];
// you are in editing/preview mode here if allowsEditing = YES
// you can remove all your custom overlay views by
myImagePickerController.cameraOverlay = nil
}
Like i said before just make sure you check if camera is ready. You can find answers here on stackoverflow on how to do it.
This code may suck so editing or alternative solutions are welcomed.
I need dev buddy to help me learn more about ios dev and ask questions. anyone interested?

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;
}

Is there a way to prevent the keyboard from dismissing?

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.

How to intercept long press on UITextView?

Total Objective-C / Cocoa Touch noob here, beware.
I'm trying to intercept when a user long presses on a UITextView (a magnifying glass then appears with the caret positioner) and then releases the touch, i.e. when normally the "Select" and "Select All" Options appear, after the magnifying glass. I want to replace this with my own custom action that is then performed.
Is this possible?
You can try something like this:
Disable the built-in long press recognizer
for (UIGestureRecognizer *recognizer in textView.gestureRecognizers) {
if ([recognizer isKindOfClass:[UILongPressGestureRecognizer class]]){
recognizer.enabled = NO;
}
}
Then add your own
UILongPressGestureRecognizer *myLongPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:<your target> action:#selector(<your custom handler>)];
[textView addGestureRecognizer:myLongPressRecognizer];
[myLongPressRecognizer release];
Swift version of #Altealice's code to disable the built-in long press recognizer:
if let actualRecognizers = self.sourcesTextView.gestureRecognizers {
for recognizer in actualRecognizers {
if recognizer.isKindOfClass(UILongPressGestureRecognizer) {
recognizer.enabled = false
}
}
}
This solution works but beware that it's gonna disable the textView interactions, so the links won't be highlighted when pressed and the text won't be selectable.
if you remove the [LongPressgesture setMinimumPressDuration:2.0]; it will work .. since the tab gesture will be called to start edit the textField ... or just implement this gesture delegate function
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
return YES;
}