paste text by code [duplicate] - iphone

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Copy and paste text with buttons
I want to make past from the clipboard by code with out toggling the screen in iPhone , Any one have any idea ?
I want to make these operation by code not like these.
Um asking if these is possible or um accessing the iOS in that case ?

[UIPasteboard generalPasteboard] provides you an instance of UIPasteboard which repents the users current clipboard content. Use it like
- (IBAction)pasteButtonPressed {
self.myTextView.text = [[UIPasteboard generalPasteboard] string];
}

The UIResponderStandardEditActions informal protocol declares the paste: method that is designed for that purpose. UITextView (along with other UIResponder subclasses) conforms to this informal protocol and thus responds to this method.
This has the advantage of managing every aspect of the pasting operation, especially pasting the text at the position of the insertion point, or replacing the selected text if any, as with a classic paste operation.
Another solution is to insert the text contained in the UIPasteboard yourself in your text view. But be sure in that case to replace the selectedTextRange (selected text or insertion point) and not replace the whole content of the UITextView.
For this purpose, use the fact that UITextView implements the UITextInput formal protocol, which declares every method needed to handle objects that manage text input (like UITextView, UITextField, etc) especially replaceRange:withText: and selectedTextRange:
NSString* pasteboardText = [[UIPasteboard generalPasteboard] string];
[self.myTextView replaceRange:self.myTextView.selectedTextRange withText:pasteboardText];

Related

Objective c - Text indentation

This question is about implementing text indentation ("The placement of text farther to the right to separate it from surrounding text") in iOS.
Take for example the following text:
This is the first section.
This is the second one,
with two lines.
This is the third.
Notice that the second row in section 2 begin farther to the right and just below the line above.
My code contains an array of NSString, each one should be display as a section with numeric bullet like above. for example:
NSArray *array = [NSArray arrayWithObjects:#"1. This is the first section.", #"2. This is the second one, with two lines.", #"3. This is the third.", nil];
I use UILable to display the text on screen.
To set the text from the array to the label, and to separate each string in a new line I use
myLabel.text = [array componentsJoinedByString:#"\n"];
Any ideas how to get this effect?
This is possible to some degree in iOS6 with - [UILabel setAttributedText:].
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.headIndent = 29;
myLabel.attributedText = [[NSAttributedString alloc] initWithString:
#"1.\tShort line.\n2.\tLong line with content that triggers wrapping.\n3.\tShort line."
attributes:#{NSParagraphStyleAttributeName: paragraphStyle}];
This adds indentation to the subsequent lines. It looks like iOS doesn't support tab stops in the same way as OSX so I'm not seeing a way to adjust the gap between the number and the text. This is probably possible in CoreText.
Of course, you could also just replace the label with a UIWebView and have full formatting control on all versions of iOS at the cost of performance.
Well I decided to implement it my self without using Core Text, I just created a view strcture that make all the indentation work by itself, and let you customize it as you want.
For all of you interested in the implementation, you can see the source code and an example project here:
ECListView Project
UILabel is not going to cut it if you have any kind of specific layout requirements. For that, you're going to need to dig into Core Text. The good news is that Core Text will let you do any kind of text layout you can imagine. The bad news is that all that power brings with it some complexity, so to use it you're going to have to invest some time learning how the framework works.
An alternative that's suitable in some situations is to use a web view to display your text. UIWebView will let you do whatever text layout you can manage using HTML and CSS.

NSString UITextView without replacing previous text

How would I go about adding text to a UITextView without replacing the previous text?
So far I have a UITextView and a UIButton that adds the text to the UITextView, but I would like the text field to append more text every time you hit the button instead of completely deleting the text and replacing it.
Here are some ways to overcome obstacles in iOS development:
Look at the documentation for the particular class you're trying to manipulate. In this case, UITextView documentation can be found within Xcode or online.
Command-Click on UITextView or any other object anywhere in your code, and it will bring you to the header file for that class. The header file will list every public method and property.
Look at your existing code. I'm assuming that since you have a button that adds text to a UITextView, you understand how to set its text. 99% of the time you'll find that any setter (mutator) methods will have a corresponding getter (accessor) method. In this case, UITextView has a method called setText: and a matching method just called text.
Finally, NSString has a convenience method called stringWithFormat: that you can use to concatenate (join) two strings, among other very useful things. %# is the format specifier for a string. For example, to combine two strings, stringOne and stringTwo, you could do the following:
NSString *string = [NSString stringWithFormat:#"%# %#", stringOne, stringTwo];
I will leave you to come up with the answer as to how to combine NSString stringWithFormat: and UITextField text and setText: to achieve what you'd like to accomplish.
Edit:
The OP was unable to figure out how to utilize the information above so a complete code sample has been provided below.
Assume you have synthesized property (possibly an IBOutlet) UITextView that you have initialized called myTextView. Assume also that we are currently in the method scope of the method that gets called (your IBAction, if you're using IB) when you tap your UIButton.
[myTextView setText:[NSString stringWithFormat:#"%# %#", myTextView.text, #"this is some new text"]];
Explanation: myTextView.text grabs the existing text inside of the UITextView and then you simply append whatever string you want to it. So if the text view is originally populated with the text "Hello world" and you clicked the button three times, you would end up with the following progression:
Initial String: #"Hello world"
Tap one: #"Hello world this is some new text"
Tap Two: #"Hello world this is some new text this is some new text"
Tap Three: #"Hello world this is some new text this is some new text text this is some new text"
If all you are doing is appending text, you might find this a little simpler:
myTextView.text = [myTextView stringByAppendingString:#"suffix\n"];
I found this on UITextView insert text in the textview text. Sadly, I have not found a way to append text directly without a wholesale replacement of the text in the UITextView. It bugs me that the effort involved is proportional to the total length of the existing string and the suffix, rather than just the suffix.
A more efficient way to append text is to use replace() at the end:
extension UITextInput {
func append(_ string : String) {
let endOfDocument = self.endOfDocument
if let atEnd = self.textRange(from: endOfDocument, to: endOfDocument) {
self.replace(atEnd, withText: string)
}
}
}
#Jack Lawrence: Your answer doesn't cover the question completely.
The example below will not scroll neatly while running off the bottom when called every second:
self.consoleView.text = [NSString stringWithFormat:#"%#%#%#", self.consoleView.text, data, #"\n"];
[self.consoleView scrollRangeToVisible:NSMakeRange(self.consoleView.text.length, 0)];
This is caused by setText replacing the original text every time thereby resetting associated contentOffsets etc.
This was possible prior to iOS 7, but since iOS 7 it seems that setText cannot be prevented from exhibiting jumpy behaviour. Appending does not seem to be an option for TextViews in this scenario?

Overriding Emoji Graphics

I want to override the emoji icons with my own custom graphics (only within my app).
From what I've read so far, one possible solution is to create a custom font extension which overrides the desired unicode characters. Preferable I would like to maintain inter-operability with CATextLayer.
Edit: Looks like custom fonts won't be my solution; fonts must be defined in gray-scale. Next possibility: Creating a custom CALayer, chunking the string into segments based on emoji code, and doing the type setting + graphics rendering manually (i.e. with core graphics and core text)
Edit: Also looking to maintain smooth scrolling performance in a table views.
I have devoted a lot of time trying to do the same. Your best bet is to replace the unicode values for the emoji in your NSString eg. \uE100 etc. with a placeholder string. You could replace the emoji encodings with an HTML Tag and use either UIWenViews or DTCoreText to draw the image inline.
I have done this, it works too, but it will be a little slow (Specially if you want to display this Label in table views.)
Here is a little starter:
Make a dictionary with UIImages as objects and placeholder strings as keys:
self.emoticonDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"happyEmoticon.png", #":)",
#"sadEmoticon.png", #":(",
#"testImg.png", #"\uE100",
nil];
__block NSString *text1 = [NSString stringWithFormat:#"<html><p>%#</p></html>",text];
[self.emoticonDict enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL *stop) {
text1 = [text1 stringByReplacingOccurrencesOfString:key withString:[NSString stringWithFormat:#"<img height= 15 width= 15 src=\"%#\">",obj]];
}];
You can at this point load this HTML into a UIWebView and you will have what you want.
[myWebView loadData:_htmlData MIMEType:#"text/html" textEncodingName:#"utf-8" baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];//do create the webview first
If the slow speed of a UIWebView is a concern, you can read ahead. In either case do look at the note towards the end of this answer.
To create a DTAttributedLabel, we do the following:
First we build a NSattributedString using the DTHTMLAttributedStringBuilder:
NSAttributedString *temp = [[[DTHTMLAttributedStringBuilder alloc] initWithHTML:text1
options:#{
DTDefaultFontFamily: #"Helvetica",
DTDefaultFontSize:#15,};
documentAttributes:nil]
generatedAttributedString];
Then you can use a DTAttributedLabel instance to display temp.
self.tempLabel.attributedString = temp;//create a DTAttributedLabel Instance called tempLabel before this, I had it as a property
My objective was to generate text label's really fast (Table Views) while supporting custom emoticons. DTAttributedLabels are fast (much faster than a UIWebView)
NOTE:
I also made a custom font where I had mapped the unicode values for the emojis to a custom glyph. To my surprise, still the default emojis were displayed. I would like to claim here that whenever iOS (CoreText) comes across a character whose value lies in the Emoji section, it draws it using the AppleColorEmoji font by default. The lack of documentation on how Apple Color Emoji font is actually drawn on iOS actually makes it difficult for me to prove this, but this seems to be a plausible explanation.
If you drop an emoji from the character palette app onto a file in textEdit, then select it and try to change the font, you see that it doesn't happen.
Similarly, if you type some text, then select it and try to change it's font to Apple Color Emoji, you'll see it doesn't happen. When I decompiled the Apple Color Emoji font, I didn't find character mappings or glyphs for textual characters (except 0-9). Somehow, even if you set a label's font as Apple Color Emoji, the font for the textual (non-emoji) part of your label's text is set to something else.
Kindly feel free to comment and share your knowledge since this region around the Apple Color Emoji font still remains very unclear.
One solution would be to use the UITextField or TextView delegate and listen to the user's input. When they type an emoji character, pop in a UIImageView inline with the text, and delete the emoji icon with the input.
There's a few mentions of this issue on Apple's private devforums (which you have access to if you're a registered member of the iOS developer program).
It sounds like the potential solution would be to explicitly set the font for whatever you're trying to display.

Restricting copy paste of string in numeric textfield

I have a textbox in which I wanted a user to enter only numbers. I have implemented the number keypad there. But if someone puts my app in the background and copies some character string from some other app and comes back to my app and pastes it, it successfully pastes the string content into my numeric textfield. How can I restrict this scenario?
#theChrisKent is close, but there's a slightly better way. Use the delegate method -textView:shouldChangeTextInRange:replacementText:. Check if replacementText contains any non-numbers, and if so return NO.
You can disable pasting altogether by following the top answer on this question: How disable Copy, Cut, Select, Select All in UITextView
Just subclass the UITextView and override this method (code stolen from above question):
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
if (action == #selector(paste:)
return NO;
return [super canPerformAction:action withSender:sender];
}
Otherwise you can implement the UITextViewDelegate protocol and implement the textViewDidChange: method and check if it's numeric. If not, undo the changes. Documentation here: http://developer.apple.com/library/ios/documentation/uikit/reference/UITextViewDelegate_Protocol/Reference/UITextViewDelegate.html#//apple_ref/occ/intfm/UITextViewDelegate/textViewDidChange:

Custom iPad 10-key popover possible

and thanks for your responses in advance.
I have been looking around for the possibility of having a 10-key, numeric only, input available when a user clicks on certain fields that do not require the use of the full size keyboard.
I know that popovers can properly display custom types of input, but does anyone know if there is a way for a standard 10-keypad to display in a popover? And if so, can you point me in the right direction.
Again, thanks in advance.
-Rick
You don't need to use popover if you try to enter numeric value in a UITextField/UITextView.
You can replace the keyboard by your own view.
You just do :
[yourTextField setInputView:myInputView];
You can have a look at KeyboardAccessory sample from apple
http://developer.apple.com/iphone/library/samplecode/KeyboardAccessory/Introduction/Intro.html
In this example, they provide an accessory view to the input view but if you modify the code and set inputView instead of inputViewAccessory, you should be able to do what you need.
If you use a UITextView, you can append text where the carret is with the following code:
NSMutableString *text = [textView.text mutableCopy];
NSRange selectedRange = textView.selectedRange;
[text replaceCharactersInRange:selectedRange withString:#"\n"];
textView.text = text;
If you use a UITextField, it seems you can only append text at the end of the string (no mean to retrieve carret position).