Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UISegmentedController freezes after pressing same segment twice

I am combining Swift code and a third party library (written in Obj-C). I have a UIViewController with u UISegmentedController in, that I want to trigger each time a segment has been pushed or the same segment was pushed again.

In my Swift code, I have the following:

override func viewDidLoad() {
        super.viewDidLoad()
        //setup
        items = ["newTab".localized,"topTab".localized,"categoryTab".localized]
        carbonTabSwipeNavigation = CarbonTabSwipeNavigation(items: items as [AnyObject], delegate: self)
        carbonTabSwipeNavigation.insertIntoRootViewController(self)
        self.style()
        self.view.userInteractionEnabled = true


        carbonTabSwipeNavigation.carbonSegmentedControl!.addTarget(self, action: #selector(OverviewFolder.changesMade), forControlEvents: UIControlEvents.ValueChanged)
    }
func changesMade() {
        switch carbonTabSwipeNavigation.carbonSegmentedControl!.selectedSegmentIndex {
        case 0:
            print("tab 1")
        case 1:
            print("tab 2")
        case 2:
            print("tab 3")
        default:
            print("nope")
        }
    }

In the library I have added the following code:

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSInteger current = self.selectedSegmentIndex;
    [super touchesEnded:touches withEvent:event];
    if (current == self.selectedSegmentIndex)
        [self sendActionsForControlEvents:UIControlEventValueChanged];
}

So basically I want to trigger a ValueChanged action every time a user presses a segment (even if it's the same segment). Currently it triggers a second time when I press the same segment, but after that the UISegmentController becomes unresponsive (can't switch segments anymore).

like image 436
SoundShock Avatar asked Nov 10 '16 12:11

SoundShock


2 Answers

What finally worked for me is the following:

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];

    [self sendActionsForControlEvents:UIControlEventTouchUpInside];
}

and

carbonTabSwipeNavigation.carbonSegmentedControl!.addTarget(self, action: #selector(OverviewFolder.changesMade), forControlEvents: UIControlEvents.TouchUpInside)
like image 81
SoundShock Avatar answered Nov 08 '22 17:11

SoundShock


You should use the touchesEnded function, which is called when the user removes a finger from the screen and use sendActions:

Objective-C

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesEnded:touches withEvent:event];

[self sendActionsForControlEvents:UIControlEventTouchUpInside];
}

Swift

override func touchesEnded(_ touches: Set<AnyHashable>, withEvent event: UIEvent) {
super.touchesEnded(touches, withEvent: event)
self.sendActions(for: .touchUpInside)
}
like image 2
GJZ Avatar answered Nov 08 '22 17:11

GJZ