delete last character of string with self-made keyboard - ios

i have a uitextfield (_nameField) and buttons a-z, space, minus, delete and ok.
the buttons a-z, space, minus have the following same ibaction:
NSString *text1 = #"";
- (IBAction)keyboardButtons:(id)sender {
if (_nameField.text.length <=14) {
if (_nameField.isEditing) {
text1 = [text1 stringByAppendingString:[sender currentTitle]];
[_nameField setText:text1];
}
}
}
works perfectly.
the delete button have this ibaction:
- (IBAction)clearButton:(id)sender {
if (_nameField.isEditing) {
text1 = #"";
[_nameField setText:text1];
}
}
ok, thats pretty simple, it sets the text of my string to #"". but i want to delete just the last character. how can i do that?

just write
text1 = [text1 substringToIndex:(text1.length -1)]

Obj-C doesn't provide a method to remove the last character, but you can achieve the same thing by taking a substring that includes all characters except the last one.
NSString* withoutLastChar = [originalString substringToIndex: [originalString length] - 1];

Related

How to pass value in uitextview using segue

I'm trying to create something in UITextView that every time the text encounter this kind of symbol "#". All text after that symbol will send to other controller.
here's my code
- (BOOL)textView:(UITextView *)aTextView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
// "Length of existing text" - "Length of replaced text" + "Length of replacement text"
NSInteger newTextLength = [self.addingText.text length] - range.length + [text length];
if([text isEqualToString:#"#"] || secondString){
secondString = true;
NSString * stringToRange = [self.addingText.text substringWithRange:NSMakeRange(0,range.location)];
// Appending the currently typed charactor
stringToRange = [stringToRange stringByAppendingString:text];
// Processing the last typed word
NSArray *wordArray = [stringToRange componentsSeparatedByString:#"#"];
self.getSecondString = [wordArray lastObject];
// wordTyped will give you the last typed object
NSLog(#"\nWordTyped : %#",self.getSecondString);
}
if (newTextLength > 50) {
// don't allow change
[aTextView resignFirstResponder];
return NO;
}
self.countChar.text = [NSString stringWithFormat:#"%li", (long)newTextLength];
return YES;
}
I get that code from here. It is perfectly work when I use NSLog but the time I click the button to send it to other controller using segue. It always show Null value. Hoping your help here. Thanks in advance
here's my button code
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
CameraViewController * cameraViewController = (CameraViewController *)[segue destinationViewController];
if([segue.identifier isEqualToString:#"createText"]){
NSLog(#"prepareForSegue: %# == %#", self.addingText.text,self.getSecondString);
cameraViewController.inputCreateText = [NSString stringWithFormat:#"%#", self.addingText.text];
cameraViewController.secondInputCreateText =[NSString stringWithFormat:#"%#", self.getSecondString];
}
}
I think your problem is you are modifying your string inside textView:shouldChangeTextInRange: which gets called for every typed in character. If your purpose is to send the string after # on tap on a button then do the calculation on button handler or inside prepareForSegue:sender:. If for some reason you want to stick to your own implementation then I would advise to put your targeted string inside NSMutableArray property created at class level so you don't loose data. And then you can combine all string inside that array like this [arrayOfStrings componentsJoinedByString:#" "].

ReactiveCocoa: limit the input length of UITextfield but allow unlimited length when selecting characters

When inputing text in Chinese, you input English characters and then select the Chinese characters, before you selecting the Chinese characters, the English characters are in a selected state(-markedRange).
Before using ReactiveCocoa, I can do it like this:
in UITextField's UIControlEventEditingChanged event callback:
const NSUInteger limitLength = 10;
NSString *tobeString = textField.text;
UITextRange *selectedRange = [textField markedTextRange];
BOOL nothingSelected = (selectedRange==nil || selectedRange.isEmpty);
if (nothingSelected) {
if (tobeString.length > addressItemNameLimitLength) {
textField.text = [tobeString substringToIndex:limitLength];
}
}
self.textField.text = textField.text;
But in MVVM with ReactiveCocoa, I can't get a reference to the UITextField in my view model, how can I get the marked range and text of the text field at the same time?
I consider logic of inputing Chinese characters as helper for user input, thus view model should not know about this.
Building on answer to your previous question, you could do something like this:
In UITextField category add signal similar to -rac_textSignal except it won't fire if there is non-empty selected range during editing:
- (RACSignal *)textSignalForChineseInput {
RACSignal* editingEventsSignal = [[[self rac_signalForControlEvents:UIControlEventEditingChanged]
filter:^BOOL(UITextField* x) {
return x.selectedTextRange == nil || x.selectedTextRange.isEmpty;
}]
merge:[self rac_signalForControlEvents:(UIControlEventAllEditingEvents & ~UIControlEventEditingChanged)]];
#weakify(self)
return [[[[[RACSignal
defer:^RACSignal *{
#strongify(self)
return [RACSignal return:self];
}]
concat:editingEventsSignal]
map:^id(UITextField* x) {
return x.text;
}]
takeUntil:self.rac_willDeallocSignal]
setNameWithFormat:#"%# -rac_textSignalForChineseInput", self.rac_description];
}
In a view:
RAC(self.textField, text) = [self.viewModel validatedTextWithSignal:self.deviceName.rac_textSignal];
In a view model:
- (RACSignal *)validatedTextWithSignal:(RACSignal *)signal {
NSUInteger kMaxLength = 5;
return [signal map:^id(NSString *text) {
return text.length <= kMaxLength ? text : [text substringToIndex:kMaxLength];
}];
}

ibaction to switch text of two labels

I have two labels: oneLabel and twoLabel. Let's say oneLabel displays '1' and twoLabel displays '2'. I'm trying to create a button that when pressed will switch the text between the labels. I'm trying:
- (IBAction)switchButton:(id)sender {
self.oneLabel.text = self.twoLabel.text;
self.twoLabel.text = self.oneLabel.text;
}
The code switches twoLabel text to oneLabel, but not oneLabel text to twoLabel. What am I missing?
I think that is because after copying twoLabel's text to oneLabel; oneLable's text has twoLabel's text and when you try to copy the text from one to two ,one has two's content and that content only is copied to two so no change is seen in twoLable. Use breakpoints and check.Try
NSString *temp = self.oneLable.text;
self.oneLable.text= self.twoLable.text;
self.twoLable.text= temp;
Set 2 temporary strings>
NSString *myText1Str, *myText2Str;
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder]; //to hide the keyboard
[self setString]; //calling the method when u hit enter or return
return YES;
}
-(void)setString{ //this method sets the current string values from the textfield
myText1Str = self.oneLabel.text;
myText1Str = self.twoLabel.text;
}
-(IBAction)switchButton :(id)sender{ //swaps the texts
self.oneLabel.text = myText2Str;
self.oneLabel.text = myText1Str;
}
Try This
-(IBAction)btnClicked:(id)sender
{
NSString *str=lbl1.text;
NSString *str1=lbl2.text;
lbl1.text=str1;
lbl2.text=str;
}

My UILabel is not displaying when my if statement is false

I have a story board that has a UITextField, UIButton, UIImage, and UILabel to display the images in an array. If you type the correct name for the image file into a text field. So, the problem is that once the text field input does not match, it should update the UILabel to display "Result not found", but it doesn't.
#import "ViewController.h"
#interface ViewController ()
{
myClass *myNewClass;
NSMutableArray *picArray;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
picArray = [#[#"Button_Red",#"Button_Green"]mutableCopy];
}
- (IBAction)displayImageAction:(id)sender
{
NSString *titleSearched = self.textSearchField.text;
NSString *titleNotHere = self.notFoundLabel.text;
//Declare a bool variable here and set
BOOL variable1;
for (int i = 0; i < picArray.count; i++)
{
NSString *currentPic = picArray[i];
if ([titleSearched isEqualToString:currentPic])
{
variable1 = YES;
}
}
if (variable1 == YES) {
//this works fine displays the image
self.outputImage.image = [UIImage imageNamed: titleSearched];
[self.textSearchField resignFirstResponder];
} else {
//problem is here its not showing when input for the array is not equal it should display a message label "Result Not Found" but it remains blank on the IOS simulator
titleNotHere = [NSString stringWithFormat:#"Result Not found"];
[self.textSearchField resignFirstResponder];
}
}
//Get rid of the texfield when done typing
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// Retract keyboard if up
[self.textSearchField resignFirstResponder];
}
Your problem is that
titleNotHere = [NSString stringWithFormat:#"Result Not found"];
simply sets the method variable titleNotHere.
What you want is
self.notFoundLabel.text=#"Result Not found";
You will also want
self.notFoundLabel.text=#"";
when the result is found.
I think you will have to SET the value to the variable
self.notFoundLabel.text = [NSString stringWithFormat:#"Result Not found"]
or
self.notFoundLabel setText:[NSString stringWithFormat:#"Result Not found"]
UILabel.text = #"whatever..." is actually converted into [UILable setText:#"whatever..."].
NSString *labelText = UILabel.text has to be thought as NSString *labelText = [UILabel text];
This:
NSString *titleNotHere = self.notFoundLabel.text;
stores the text from the label into a variable, but updating that variable again will not change the label text - it only changes what that variable points to.
You need to explicitly update the label text:
self.notFoundLabel.text = #"Result Not found";
note also that this uses a string literal - you don't need to use a format string as you aren't adding any parameters to it.
Also, when checking booleans, don't use if (variable1 == YES) {, just use if (variable1) { (it's safer).

Delete text from backspace

I can't find tutorial that does this. I have...
UIbutton
UItext.text
I want to make my own KEYBOARD user interface without iphone keyboard. I want to press the UIbutton(keyboard "delete" key or backspace) from text. Not ease the whole thing like UIText.text = #"". I've seen programmers give the wrong code. I'm looking for something like Visual Basic Sendkeys {Delete}. How do I do this on iphone button? http://gigaom.com/apple/iphone-os-where-the-delete-key-belongs/
For example:
Text1
Text<=
Tex<=
Implement the following method to delete the last character.
- (NSString *)deleteLastChar:(NSString *)str {
if (![str length]) return #"";
return [str substringToIndex:[str length]-1];
}
You can then use that on your text field's text property e.g:
textField.text = [self deleteLastChar:textField.text];
if ([textField.text length] != 0) {
textField.text = [textField.text substringToIndex:[textField.text length]-1];
}

Resources