SoundShock SoundShock - 4 months ago 31
Swift Question

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() {
items = ["newTab".localized,"topTab".localized,"categoryTab".localized]
carbonTabSwipeNavigation = CarbonTabSwipeNavigation(items: items as [AnyObject], delegate: self)
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")

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).


What finally worked for me is the following:

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

    [self sendActionsForControlEvents:UIControlEventTouchUpInside];


carbonTabSwipeNavigation.carbonSegmentedControl!.addTarget(self, action: #selector(OverviewFolder.changesMade), forControlEvents: UIControlEvents.TouchUpInside)