UIPasteBoard string never get a right value after cut a text - ipad

i have cut a text in a textview using UIMenuController and i want to paste it in another place. But the UIPasteBoard string never get a right value. FYI, it just happen in cut process, but it's no problem in copy.
In example :
i have copied "XYZ" and paste it, the UIPasteBoard string is contain the right value, there is "XYZ"
then, i want to cut "ABC" and paste it, but the UIPasteBoard string contain the wrong value, it stil "XYZ" not "ABC", and the xcode output give me a text Webcore NSBeep()!
I dont understand why it can happen, can somebody give me some clue? thank you
UPDATE
i just use canPerformAction method :
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{
return [super canPerformAction:action withSender:sender];
}

This is how you should be setting the pasteboard with simple text:
[[UIPasteboard generalPasteboard] setString:#"XYZ"];
Using your own UIMenuController:
UIMenuItem * copy = [[UIMenuItem alloc] initWithTitle:#"Copy Text" action:#selector(copyText:)];
UIMenuController * actionMenu = [UIMenuController sharedMenuController];
[actionMenu setMenuItems:[NSArray arrayWithObjects: copy, nil]];
[actionMenu setTargetRect:someButton.frame inView:someButton.superview];
[actionMenu setArrowDirection:UIMenuControllerArrowDefault];
[actionMenu setMenuVisible:YES animated:YES];
-(void)copyText:(id)sender {
UIButton * button = (UIButton*)sender;
[[UIPasteboard generalPasteboard] setString:button.titleLabel.text];
}

In example : i have copied "XYZ" and paste it, the UIPasteBoard string
is contain the right value, there is "XYZ"
then, i want to cut "ABC" and paste it, but the UIPasteBoard string
contain the wrong value, it stil "XYZ" not "ABC", and the xcode output
give me a text Webcore NSBeep()!
Answer: Webcore NSBeep()! because the "ABC" is not copied into your clipboard and the error notified with a beep (IMHO which is not wise way of notifying errors by any platform, it would have been any visual indication)
And please note : NSBeep() is part of the ApplicationKit framework which doesn't exist on the iPhone.

Related

Xcode IOS Create 3 buttons to replace keyboard and text box

I am using an app to lock, unlock, and open the trunk of my car. The only problem is that I can't figure out how to modify the Xcode project so there are 3 buttons. Basically right now if I type "U" then enter- the car unlocks, "L" then enter- the car locks, and "T" then enter- the trunk opens. I want to add three buttons that simulate these three things and eliminate the typing all together. If you want to see my adruino or xcode project code I can upload those. I have put some code about the text box below.
BOOL)textFieldShouldReturn:(UITextField *)textField
{
NSString *text = textField.text;
NSNumber *form = [NSNumber numberWithBool:NO];
NSString *s;
NSData *d;
if (text.length > 16)
s = [text substringToIndex:16];
else
s = text;
d = [s dataUsingEncoding:NSUTF8StringEncoding];
if (bleShield.activePeripheral.state == CBPeripheralStateConnected) {
[bleShield write:d];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:text, TEXT_STR, form, FORM, nil];
[tableData addObject:dict];
[_tableView setContentOffset:CGPointMake(0, CGFLOAT_MAX)];
NSLog(#"%f", _tableView.contentOffset.y);
[self.tableView reloadData];
}
textField.text = #"";
return YES;
Thanks for the help!
Your view controller probably has a textFieldShouldReturn method which is taking the string value from the text field and building a parameter to a call that initiates sending the command. If not this method then perhaps its action method linked to the text field.
You'll need to duplicate parts of that code into a method that receives a string parameter instead of taking it from the text field, say named sendLockCommand:(NSString *)commandString (assuming you're coding in Objective-C, also like that repo).
Make action methods for your buttons, something like lockDoors, unlockDoors, openTrunk, in each call [self sendLockCommand:#"L"], each with the appropriate string. Wire up the buttons to those actions and you're good to go.

Making a button read a string from an array

I'm a beginner developer for iOS. I'm using objective c to develop an app. I want a button to be able to read a string from an array. What I mean by this is NOT to set the string as what the button displays. I want it to be able to get the string so I can use AVSpeechSynthesizser to read the string aloud. Thanks in advance
You don't provide any code or details about your problem.
I have to make assumption that you just want to read something from array while button is tapped.
Either using storyboard to create the button object and its handler or manually add the handler.
Let's say you have the button object named 'exampleButton', if you choose manually add the handler,
[exampleButton addTarget:self action:#selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
Let's say your array name is exampleArray, and you want to access the first element.
EDIT:
use firstObject instead objectAtIndex:0 since the latter one will crash the app if the array is empty.
- (IBAction)buttonTapped:(id)sender {
// becareful, if the array is empty, firstObject will return nil.
// If you use [exampleArray objectAtIndex:0], it will crash
id obj = [exampleArray firstObject];
if ([obj isKindOfClass:[NSString class]]) {
NSLog(#"%#", obj); // now you have the string object.
}
}
You have to learn more if you still cannot get yourself started with above code.

Creating HTML email from UITextField text

I'm a novice and recreational programmer. I am trying to create an app for iOS that populates the text from my UITextFields. I have 3 the actionField, impactField, and result Field. I'd like for each to have their own line, if possible.
I looked at a similar answer, but it was not any help for me. Does anyone have any tutorials or advice?
- (IBAction)backgroundTap: (id)sender {
[self.actionField resignFirstResponder];
[self.impactField resignFirstResponder];
[self.resultField resignFirstResponder];
}
- (IBAction)sendBullet:(id)sender {
NSString *emailTitle = #"Email";
NSString *messageBody = #"Title";
NSArray *toRecipients = [NSArray arrayWithObject:#"email"];
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setMessageBody:messageBody isHTML:NO];
[mc setToRecipients:toRecipients];
[self presentViewController:mc animated:YES completion:NULL];
MHinton,
Before you proceed, you should take a look at HTML syntax, there are hundreds of thousands of tutorials out there since this has been around for decades. It's fairly easy to pick up. You can start HERE
NOTE It's best to test HTML emails on a device as the simulator can be kind of wonky with the MFMailComposeViewController
Secondly, grabbing the text from a text view or other forms of strings is fairly easy, again, thousands of tutorials out there. Specifically for Obj C you do it as follows :
1) Create an outlet for your textfields
#interface YourViewController: UIViewController
#property (nonatomic, retain) IBOutlet UITextField *actionField
#end
2) Then you can reference it anywhere in your implementation file (.m) like this :
NSString *emailMessageBody = self.actionField.text;
DISPLAYING TEXT IN HTML FORMAT FOR EMAILS
Creating an HTML formatted email is relatively easy as long as you spend about 15 minutes learning HTML syntax.
If you want to insert your UITextFields in different lines you implement the HTML equivalent to line break (or pressing the enter button): <br>
So an example string to pass in the MFMailComposeViewController will look like this:
NSString *emailMessageBody = [NSString stringWithFormat:#"The retrieved text from actionField is : <br><strong><font color=\"red\">'%#'</font><br></strong><br> The retrieved text from impactField is : <br>%#<br> The retrieved text from resultField is : <br>%#<br>", self.actionField.text, self.impactField.text, self.resultField.text];
Your options are limitless here, as long as you know HTML syntax. So whats going on here?
<br> creates the line break
<strong> creates a bold style text and to end the format you place </strong> after the last word you want bold faced
<font> self explanatory; you have to end this style format as well.
You call it in the MFMailComposeViewController per usual, however you must explicitly set the email to HTML so all the HTML tags can be stripped from formatting and so it doesn't display it as plain text.
[mc setMessageBody:emailMessageBody isHTML:YES];
Other commonly used HTML tags are :
<style> for formatting
<p> for paragraphs
<h1> for headers
<mark> for highlighting
<small> for small text
<i> or <em> for italics or emphasized
Refer to the link above for more HTML tags
SWIFT SYNTAX
var emailMessageBody = NSString(format:"The retrieved text from actionField is : <br><strong><font color=\"red\">'%#'</font><br></strong><br> The retrieved text from impactField is : <br>%#<br> The retrieved text from resultField is : <br>%#<br>", actionField.text, impactField.text, resultField.text) as String
mailComposerVC.setMessageBody(emailMessageBody, isHTML: true)
All you need to do is build a string from the text fields:
NSString *messageBody = [NSString stringWithFormat:#"Action: %#\nImpact: %#\nResult: %#", self.actionField.text, self.impactField.text, self.resultField.text];
Update the format string as needed. What I present here is just one example.
The \n is a special value in a string that means "newline". This means the string I show will consist of three lines of text.

How to programmatically make text selectable and provide popup menus to go to another app

I am trying to implement a feature in iOS project that when you select a piece of text and highlight it you can then choose from the menu options to use another app like the default dictionary. Is it possible to do this? If so where can I find such documentation or tutorials?
You are describing the iOS menu. Look at the documentation on classes such as UIMenu, UIMenuItem, and UIMenuController.
I've found a solution to my problem.
Thanks to the author of this article:
http://blog.studiovillegas.com/2014/02/06/ios-uipasteboard-uimenucontroller-and-uimenuitem/
To add a custom menu item on to the default menu controller.
ViewController.h
- (void)longPressGestureRecognizer:(UIGestureRecognizer *)recognizer
{
UIMenuItem *mi = [self.label menuItemOpenPleco];
UIMenuController *menuController = [UIMenuController sharedMenuController];
menuController.menuItems = #[mi];
}
PasteboardLabel {h,m}
#interface PasteboardLabel : UILabel
- (UIMenuItem *)menuItemOpenPleco;
#end
#implementation PasteboardLabel
- (UIMenuItem *)menuItemOpenPleco
{
return [[UIMenuItem alloc] initWithTitle:#"Open Pleco" action:#selector(openPleco:)];
}
- (void)openPleco:(id)sender
{
NSString *selectedText = [self textInRange:[self selectedTextRange]];
UIPasteboard *pb = [UIPasteboard generalPasteboard];
pb.string = selectedText;
NSString *urlString = [NSString stringWithFormat:#"plecoapi://x-callback-url/q?s=%#", pb.string];
NSURL *url = [[NSURL alloc] initWithString:urlString];
[[UIApplication sharedApplication] openURL:url];
}
#end
I've found that there's a dearth of examples of adding custom menu items, or explanations of how they work. So I wanted to resolve that by sharing a few important tidbits then showing an example.
The UIMenuController "talks" with UIViews, not with UIViewControllers. This means that your UIMenuController related code needs to go into subclasses of UIView rather than a UIViewController.
Notice the word The at the start of my prior example. There's only one UIMenuController, a singleton which is shared from when your application first starts until it ends. This means that you should only add your item once, and that you shouldn't be writing over the existing array of items.
The appearance of the button in the UIMenu is based on whether or not the UIView that was tapped responds to the selector. This means you need to implement the method if you want the button to appear, and that you don't need to worry about it appearing when unrelated views are tapped unless you pick a selector name for which other UIViews also have methods.
So, having said all that, I made a subclass of a UITextView (which means its a subclass of UIView per my first bullet) and then I gave it this initialize method, along with an implementation for my selector.
+ (void)initialize {
static dispatch_once_t addInsert;
dispatch_once(&addInsert, ^{
UIMenuController *mController = [UIMenuController sharedMenuController];
UIMenuItem *insert = [[UIMenuItem alloc] initWithTitle:#"Insert..."
action:#selector(insert:)];
mController.menuItems = [mController.menuItems arrayByAddingObject:insert];
});
}
- (void)insert:(id)sender {
NSLog(#"Insert... pressed!");
}
The important points above here:
It's in the class initialize method, which is called by the runtime before the first time any other method in your class is invoked. In practice means the code is handled just before the first time an instance of your custom view will be appearing on screen.
I added a dispatch_once guard around it. If my class is subclassed, it's possible that those subclasses will call this initialize method. Maybe those subclasses show up before this one does, so I don't want to prevent the initialize method from running then. I just want to prevent it from running multiple times. Thus why I wrapped the code in a dispatch_once.
I didn't just set the menuItems to a new array of items - I assigned it to a new array of items that extended the existing array of items with my new item.
Hope you find all of that helpful. It's not very complicated, and you can certainly go about implementing my second point in other ways - I tried to pick a way that seemed safest to me, but there are certainly simpler ways of doing it.

iPhone SDK releasing NSString

I'm new to Objective C and I have a simple question about memory management.
This is a simple method for a Button which changes a UILabel with the text in a UITextField.
-(IBAction) setLabel
{
NSString *inputText = [[NSString alloc]initWithString:myTextField.text];
[myLabel setText:inputText];
[inputText release];
}
This code works fine. But If I change this code to following,
-(IBAction) setLabel
{
NSString *inputText = [[NSString alloc]initWithString:#"some string value"];
inputText = myTextField.text;
[myLabel setText:inputText];
[inputText release];
}
Then application crashes on runtime. I have to remove the line [inputText release]; to run application without crashing.
As far as I know if I created something with 'alloc' I have to release it. But here, if I release that string app crashes.Could someone please explain the reason?
Thanks in advance
The reason that the release is crashing is because you're reassigning inputText to myTextField.text. The call to release is now releasing that string instead of the one allocated on the first line of setLabel. If you use another variable for that assignment, it should fix the crash.
I know this is not a direct answer to your question but you should try to use the autorelease pool to not have to worry about these details. Thus, if you had written your code as follows:
-(IBAction) setLabel
{
NSString *inputText = [NSString stringWithString:myTextField.text];
[myLabel setText:inputText];
}
the code is more readable and, moreover, you are not responsible for releasing the inputText string instance.

Resources