custom iPhone backspace and enter buttons - iphone

i have problem with the custom backspace and enter buttons on custom iPhone keyboard ,
The Backspace : my codes just remove characters at the end of the line not from the cursor location .
if ([textView.text length]>0) textView.text = [textView.text substringToIndex:([textView.text length]-1)];
and read this question Custom keyboard iphone , having problem with backspace button in UITextView but didn't solve my problem .
The Enter : i have same problem like backspace the enter button just the inserts new line at the end of sentence not not from the cursor location .
textView.text = [NSString stringWithFormat:#"%#\n", textView.text];
how should i change my codes to work fine ? thank you
EDIT :
//BACKSPACE BUTTON CODE :
NSRange deleteRange = textPad.selectedRange;
deleteRange.length -= 1;
if ([textPad.text length]>0) textPad.text = [textPad.text stringByReplacingCharactersInRange:deleteRange withString:#""];

here is the best iphone custom backspace code :D :
NSRange deleteRange = textPad.selectedRange;
if (deleteRange.length >0)
textPad.text = [textPad.text stringByReplacingCharactersInRange:deleteRange withString:#""];
else
if (deleteRange.location > 0)
textPad.text = [textPad.text stringByReplacingCharactersInRange:NSMakeRange(deleteRange.location-1,1)
withString:#""];
deleteRange.location--;
deleteRange.length = 0;
textPad.selectedRange = deleteRange;

textView.text = [textView.text stringByReplacingCharactersInRange:textview.selectedRange withString:#"\n"]; // Replace the selected characters with a new line
or
textView.text = [textView.text stringByReplacingCharactersInRange:textview.selectedRange withString:#""]; // Delete the selected character

You can use the UITextView selectedRange method to determine the beginning and end of the selected text, and delete from that range instead of from the end of the string.

Related

Trimming NSString with multiple conditions

I'm having a hard time with trimming some characters from a NSString. Given an existing text view with text in it, the requirements are:
Trim leading spaces and newlines (Basically ignore any leading whitespace and newlines)
Copy up to max of 48 chars into the new string OR until a newline is encountered.
I have found that I could do the first requirement from another SO question here with the code:
NSRange range = [textView.text rangeOfString:#"^\\s*" options:NSRegularExpressionSearch];
NSString *result = [textView.text stringByReplacingCharactersInRange:range withString:#""];
However, I'm having trouble with doing the 2nd requirement. Thank you!
This will do what your looking to do. Also it is an easier way to trim leading whitespace and newlines.
NSString *text = textView.text;
//remove any leading or trailing whitespace or line breaks
text = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//find the the range of the first occuring line break, if any.
NSRange range = [text rangeOfString:#"\n"];
//if there is a line break, get a substring up to that line break
if(range.location != NSNotFound)
text = [text substringToIndex:range.location];
//else if the string is larger than 48 characters, trim it
else if(text.length > 48)
text = [text substringToIndex:48];
This should work. Basically what it does is it loops through the characters in the text of the textview and checks if the character it's currently on is a newline character. It also checks if it has reached 48 characters yet. If the character is not a new line character and it has not reached 48 characters yet, then it adds the character to a result string:
NSString *resultString = [NSString string];
NSString *inputString = textView.text;
for(int currentCharacterIndex = 0; currentCharacterIndex < inputString.length; currentCharacterIndex++) {
unichar currentCharacter = [inputString characterAtIndex:currentCharacterIndex];
BOOL isLessThan48 = resultString.length < 48;
BOOL isNewLine = (currentCharacter == '\n');
//If the character isn't a new line and the the result string is less then 48 chars
if(!isNewLine && isLessThan48) {
//Adds the current character to the result string
resultString = [resultString stringByAppendingFormat:[NSString stringWithFormat:#"%C", currentCharacter]];
}
//If we've hit a new line or the string is 48 chars long, break out of the loop
else {
break;
}
}

Get first sentence of textview

I am trying to get the first sentence of a text view. I have the following code but am getting an out of bounds error. Thank You. Or are there any ways that aren't really complex.
-(IBAction)next:(id)sender
{
NSRange ran = [[tv.text substringFromIndex:lastLocation] rangeOfString:#". "];
if(ran.location != NSNotFound)
{
NSString * getRidOfFirstHalfString = [[tv.text substringFromIndex:lastLocation] substringToIndex:ran.location];
NSLog(#"%#",getRidOfFirstHalfString);
lastLocation+=getRidOfFirstHalfString.length;
}
How about:
NSString *finalString = [[tv.text componentsSeparatedByString:#"."] objectAtIndex:0] // Get the 1st part (left part) of the separated string
Go through the textview's text and divide the text into separate components where you find a period by calling componentsSeperatedByString on tv.text. You want the first sentence, which would be the 0th object in the array.
I know you've already accepted an answer to this question, but you might want to consider using the text view's tokenizer instead of just searching for the string ". " The tokenizer will automatically handle punctuation like !, ?, and closing quotes. You can use it like this:
id<UITextInputTokenizer> tokenizer = textView.tokenizer;
UITextRange *range = [tokenizer rangeEnclosingPosition:textView.beginningOfDocument
withGranularity:UITextGranularitySentence
inDirection:UITextStorageDirectionForward];
NSString *firstSentence = [textView textInRange:range];
If you want to enumerate all of the sentences, you can do it like this:
id<UITextInputTokenizer> tokenizer = textView.tokenizer;
UITextPosition *start = textView.beginningOfDocument;
while (![start isEqual:textView.endOfDocument]) {
UITextPosition *end = [tokenizer positionFromPosition:start toBoundary:UITextGranularitySentence inDirection:UITextStorageDirectionForward];
NSString *sentence = [textView textInRange:[textView textRangeFromPosition:start toPosition:end]];
NSLog(#"sentence=%#", sentence);
start = end;
}
Try checking that the substring was actually found.
NSRange ran = [tv.text rangeOfString:#". "];
if(ran.location != NSNotFound)
{
NSString * selectedString = [tv.text substringToIndex:ran.location];
NSLog(#"%#",selectedString);
}
You could alternatively try using NSScanner like this:
NSString *firstSentence = [[NSString alloc] init];
NSScanner *scanner = [NSScanner scannerWithString:tv.text];
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:#"."];
[scanner scanUpToCharactersFromSet:set intoString:&firstSentence];
I'm not sure if you want this, but since you want the first sentence, you could append a period (you probably know how to do this, but it doesn't hurt to show it anyway):
firstSentence = [firstSentence stringByAppendingFormat:#"."];
Hope this helps!
PS: If it didn't work for you, maybe the text view doesn't actually contain any text.

How to add UILabel between two strings

i have this code to show some texts in a UITextview..i just want to add a UILabel between these strings.i am getting text in this formate, 1 this is first text 2 this is second text 3 this is third text,,i want to add or append UILabel between numeric character and text.my code for showing text is
NSMutableString *combined = [NSMutableString string];
for(NSUInteger idx = 0; idx < [delegatee.allSelectedVerseEnglish count]; idx++) {
[combined appendFormat:#" %d %#",
idx + 1,
[delegatee.allSelectedVerseEnglish objectAtIndex:idx]];
}
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
NSNumber * n = [f numberFromString:combined];
NSLog(#"N: %#", n);
maintextview.text =combined;
combined is the text in the above formate ,and maintextview is the UITextview.
am also getting the string range between two sentence
- (void)textViewDidEndEditing:(UITextView *)textView
{
if (textView == maintextview) {
mainpopupview.frame =CGRectMake(0, 0, 768, 1004) ;
[self.view addSubview:mainpopupview];
NSRange selectedRange = [textView selectedRange];
NSString *backString = [maintextview.text substringToIndex:selectedRange.location];
NSRange backRange = [backString rangeOfString:#" " options:NSBackwardsSearch];
NSRange backRangee = [backString rangeOfString:#" " options:NSBackwardsSearch];
int myRangeLenght = backRangee.location - backRange.location;
NSRange myStringRange = NSMakeRange (backRange.location, myRangeLenght);
NSString *forwardString = [maintextview.text substringFromIndex:backRange.location];
NSLog(#"%#",[[forwardString componentsSeparatedByString:#" "] objectAtIndex:1]);
NSLog (#"%#", [maintextview.text substringWithRange:myStringRange]);
NSString * myStringTxt = [[forwardString componentsSeparatedByString:#" "] objectAtIndex:1];
NSLog(#"1 %#", myStringTxt);
// maintextview.textColor = [UIColor yellowColor];
NSRange myStringRangee = [maintextview.text rangeOfString:myStringTxt];
[maintextview select:self];
maintextview.selectedRange = myStringRangee;
is there any way to do this.
Thanks in advance.
I don't know what user interaction you need here, but if you're just displaying the text for the user, but could you replace your UITextView with a UIWebView (loading static text via loadHTMLString:baseURL:, using html markup to set the color of the text)? I refer to the UITextView documentation:
This class does not support multiple styles for text. The font, color,
and text alignment attributes you specify always apply to the entire
contents of the text view. To display more complex styling in your
application, you need to use a UIWebView object and render your
content using HTML.
If you really need to do this with separate UI controls (much more complicated than just using a UIWebView) you don't "insert" the UILabel in the text, but rather you'd probably have one control for the text up to the point of the color change, another control for the text of a different color or what have you, another control for the rest of the text. It would get hairly pretty quickly (unless it was laid out like a grid, and even then it's a hassle compared to a UIWebView).

How to detect UISearchBar is containing blank spaces only

How to detect if UISearchBar contains only blank spaces not any other character or string and replace it with #""?
You can trim the string with a character set containing whitespace using the NSString stringByTrimmingCharactersInSet message (using the whitespaceCharacterSet):
NSString * searchString = [searchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if (![searchString length])
// return ... search bar was just whitespace
You can check as
[yourSearchBar.text isEqualToString:#""]
Hope it helps.
if([searchBar.text isEqualToString:#""] && [searchBar.text length] ==0){
// Blank Space in searchbar
else{
// Do Search
}
Use isEqualToString method of NSString
Use stringByTrimmingCharactersInSet to trim the character from NSString.
- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set
Use as below.
NSString* myString = mySearchBar.text
myString = [myString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Here's how you detect and replace it: (assuming the UISearchField is called searchBar)
NSString*replacement;
if ([searchBar.text isEqualToString:#" "])
{
replacement = [NSString stringByReplacingOccurancesOfString:#" " withString:#""];
}
searchBar.text = replacement;
Have a look in the Apple Documentation for NSString for more.
Edit:
If you have more than once space, do this:
NSString *s = [someString stringByReplacingOccurrencesOfString:#" "
withString:#""
options:NSRegularExpressionSearch
range:NSMakeRange(0, [someString length])
];
searchBar.text = s;
This worked for me: if you are using #"" or length already to control say a button then this version really does detect the whitespace, if a space has been entered...
if([activeField.text isEqualToString:#" "] && [activeField.text length] ==1){
// Blank Space in searchbar
{
// an alert example
}

Custom keyboard and type letters

every one i create custom keyboard and i have problem
iam using my keyboard as textview.inputView = myKeyboardView;
my keyboard buttons have this code :
NSMutableString *text = [textPad.text mutableCopy];
NSRange selectedRange = textPad.selectedRange;
[text replaceCharactersInRange:selectedRange withString:#"A"];
textPad.text = text;
[text release];
so the problem is when i want edit a word from middle of my sentence if i select a word and add some letters to that my button write only ONE Character and if i write some other letters that begin end of sentence ! what can i do to solve this problem ?
//EDIT//:
PROBLEM SOLVED
My first guess is that you need to set selectedRange. Also consider using convenience constructors rather than explicitly creating mutable copies — you only mutate it once so it's not likely to be any more efficient.
NSString *text = textPad.text;
NSRange selectedRange = textPad.selectedRange;
NSString *replacement = #"A";
text = [text stringByReplacingCharactersInRange:selectedRange withString:replacement];
selectedRange = (NSRange){selectedRange.location + replacement.length, 0};
textPad.text = text;
textPad.selectedRange = selectedRange;