سؤال

My iOS app has a form with about a dozen fields and I wanted to add "Previous"/"Next" buttons above the keyboard to help users move between fields. I have something like this:

for (UITextField *t in _textfields) {
    t.delegate = self;

    UIToolbar *toolbar = [[UIToolbar alloc] init];
    [toolbar setBarStyle:UIBarStyleBlackTranslucent];

    UISegmentedControl *segControl = [[UISegmentedControl alloc] initWithItems:@[@"Previous", @"Next"]];
    [segControl addTarget:self action:@selector(switchTextField:) forControlEvents:UIControlEventValueChanged];
    segControl.segmentedControlStyle = UISegmentedControlStyleBar;
    segControl.tag = [_textfields indexOfObject:t];
    if (segControl.tag == 0) [segControl setEnabled:NO forSegmentAtIndex:0];
    else if (segControl.tag == [_textfields count] - 1) [segControl setEnabled:NO forSegmentAtIndex:1];

    [segControl sizeToFit];

    UIBarButtonItem *segItem = [[UIBarButtonItem alloc] initWithCustomView:segControl];

    UIBarButtonItem *flexButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    UIBarButtonItem *doneButton =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self.view action:@selector(endEditing:)];
    [toolbar setItems:@[segItem, flexButton, doneButton]];
    [toolbar sizeToFit];
    [t setInputAccessoryView:toolbar];
}

The problem I'm having is that every so often one of the segments stops working. The method switchTextField just does not get called, the button looks normal, not disabled, but the touches do not register. Sometimes it's the "previous" button, sometimes it's the "next" one, never both at the same time, and sometimes they both work fine. Once one of the buttons gets stuck, the only way to (temporarily) fix it is to tap another textfield without the use of the toolbar or dismiss the keyboard and start editing again. What could be the problem?

هل كانت مفيدة؟

المحلول

A segmented control is not a good choice when you really want the behavior of a UIButton for your prev/next controls.

What I think is happening is that you are initializing the toolbar with the segmented control and no segment selected. So when you tap prev/next the first time, the value changes and that segment is selected for that specific segmented control. As you continue to tap prev/next, eventually you get to a segmented control that already has a segment selected and that segment will not fire a value changed event when tapped because it is already the selected segment.

You can explicitly deselect the selected segment in your switchTextField: method (make sure you don't trigger switchTextField: recursively) or you can change your implementation to use UIButton objects for prev/next instead of the segmented control.

I recommend going with UIButton.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top