Toolbar with “Previous” and “Next” for Keyboard inputAccessoryView

后端 未结 7 1742
面向向阳花
面向向阳花 2020-12-02 20:53

I\'ve been trying to implement this toolbar, where only the \'Next\' button is enabled when the top textField is the firstResponder and only the \'Previous\' button is enabl

7条回答
  •  -上瘾入骨i
    2020-12-02 21:36

    Okay, after looking at the brilliant BSKeyboardControls, I tried implementing the enabling and disabling of the segmented control in textFieldDidBeginEditing, instead of where my @selector was. I also introduced a variable for the segmented control. It works now. Here's the amended code snippet:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        [self.topText becomeFirstResponder];
    }
    
    - (void)didReceiveMemoryWarning
    {
        [super didReceiveMemoryWarning];
    
    }
    
    - (UIToolbar *)keyboardToolBar {
    
        UIToolbar *toolbar = [[UIToolbar alloc] init];
        [toolbar setBarStyle:UIBarStyleBlackTranslucent];
        [toolbar sizeToFit];
    
        self.segControl = [[UISegmentedControl alloc] initWithItems:@[@"Previous", @"Next"]];
        [self.segControl setSegmentedControlStyle:UISegmentedControlStyleBar];
        self.segControl.momentary = YES;
    
        [self.segControl addTarget:self action:@selector(changeRow:) forControlEvents:(UIControlEventValueChanged)];
        [self.segControl setEnabled:NO forSegmentAtIndex:0];
    
        UIBarButtonItem *nextButton = [[UIBarButtonItem alloc] initWithCustomView:self.segControl];
    
        NSArray *itemsArray = @[nextButton];
    
        [toolbar setItems:itemsArray];
    
        return toolbar;
    }
    
    - (void)changeRow:(id)sender {
    
        int idx = [sender selectedSegmentIndex];
    
        if (idx) {
            self.topText.text = @"Top one";
            [self.bottomText becomeFirstResponder];
        }
        else {
            self.bottomText.text =@"Bottom one";
            [self.topText becomeFirstResponder];
        }
    }
    
    
    -(void)textFieldDidBeginEditing:(UITextField *)textField {
    
        if (!textField.inputAccessoryView) {
    
            textField.inputAccessoryView = [self keyboardToolBar];
        }
        if (textField.tag) {
    
            [self.segControl setEnabled:NO forSegmentAtIndex:1];
            [self.segControl setEnabled:YES forSegmentAtIndex:0];
        }
    }
    

提交回复
热议问题