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).
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)
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With