Enabling UIBarButtonItem when entering text

I try to disable my submit button (UIBarButtonItem inside the toolbar) whenever there is no input in the "userInput" UITextField and is activated when it is. Here is the code I wrote - I cannot understand why it does not work.

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

if (userInput.text.length >0) {
    [sendButton setEnabled:YES];
}else{
    [sendButton setEnabled:NO];
}

}

Im also getting a warning saying that "control reaches the end of a non-void function".

Im very new to xcode and programming, so I'm not sure what this tells me.

Thanks for any help!

+3
source share
4 answers

shouldChangeCharactersInRange , , ( ) . , , YES .

control reaches end of non-void function

, non-void, - . , .

, , , . , , .

userInput.text , , . , .

NSString *newText = [textField.text stringByReplacingCharactersInRange:range withString:string]);

:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *newText = [textField.text stringByReplacingCharactersInRange:range withString:string]; 
    BOOL isFieldEmpty = [newText isEqualToString:@""];
    sendButton.enabled = !isFieldEmpty;
    return YES;
}
+3

ok set enable NO in vieWillAppear

-(void)viewWillAppear:(BOOL)animated
{
  [self.sendButton setEnabled:NO];

}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

if (userInput.text.length >0) {
    [self.sendButton setEnabled:YES];
}else{
    [self.sendButton setEnabled:NO];
    }
   return YES;
}

UIBarButton IBOUtlet

.h

UIBarButton *sendButton;

@property(nonatomic,retain) IBOutlet UIBarButton *sendButton;

.m

@synthesize sendButton;

-(void)dealloc
{
  [self.sendButton release];
  [super dealloc];
}

textField IB.

0
 -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    if (userInput.text.length >0) {
        [sendButton setEnabled:YES];
    }else{
        [sendButton setEnabled:NO];
    }
    return YES;
    }
0

() UITextView UIBarButtonItem .

IBAction :

- (void)textChanged:(id)sender
{
     if ( [self.someTextField.text length] > 0 )
         [self.someBarButtonItem setEnabled:YES];
     else [self.someBarButtonItem setEnabled:NO];
}

Connect the UITextView Edit Changedevent to the textChanged:one you just created. Edit Changedeven fires when characters are entered in UITextField, you check the length of the text and turn on / off UIBarButtonItemwhen the text field has some text.

You can also viewDidLoad:check the initial length of the text and enable / disable the button depending on the text.

Hope this helps. This works for me on iOS 6.1.

0
source

All Articles