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)
}
Related
I am currently developing an iOS app using swift. I used override to write my own tocuhesBegan and tochesEnded functions. Now when I use self.button.
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
super.touchesBegan(touches, withEvent: event)
for touch in touches {
var tap = touch as? UITouch
var touchPoint: CGPoint = tap!.locationInView(self)
self.touchDown(touchPoint)
}
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
super.touchesEnded(touches, withEvent: event)
self.releaseTouch()
}
override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {
super.touchesCancelled(touches, withEvent: event)
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
super.touchesMoved(touches, withEvent: event)
}
func touchDown(point: CGPoint){
if rippleEffect == true {
touchView.frame = touchViewInitFrame
self.addSubview(touchView)
var touchViewFrameXPosition: CGFloat = point.x - (frame.size.width) / 2
println("X position = \(touchViewFrameXPosition)")
var touchViewFrameYPosition: CGFloat = -(self.frame.size.width - self.frame.size.height) / 2
touchViewFrame = CGRectMake(touchViewFrameXPosition, touchViewFrameYPosition, frame.size.width, frame.size.width)
UIView.animateWithDuration(0.25, delay: 0.0, options: .CurveEaseInOut, animations: {
self.touchView.frame = self.touchViewFrame
}, completion: nil)
}
}
func releaseTouch(){
if rippleEffect == true {
UIView.animateWithDuration(0.0, delay: 0.0, options: .CurveEaseInOut, animations: {
self.touchView.removeFromSuperview()
}, completion: nil)
}
}
it doesn't go to the function I specified in the selector. Is anyone else having this issue or does anyone know what's going on?
Here is the code that I used where I am having the issue. It is a subclass of UIButton.
If you override any of the touches methods, you are supposed to override all four and call super.
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[super touchesBegan:touches withEvent:event];
//your code
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
[super touchesEnded:touches withEvent:event];
//your code
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
[super touchesMoved:touches withEvent:event];
//your code
}
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{
[super touchesCancelled:touches withEvent:event];
//your code
}
You probably have two different handles for your view and your button, to prove that try to touch anywhere else in the screen and your touch will be detected, however while pressing the button the touch is handle and never pass to the other handlers. You have to options, intercept all messages and handle if it should be passed or not for the original handles before/after you do what you need to do, or implement the button handler and make it pass the message up the chain:
From the apple documentation:
Overriding hit-testing ensures that the superview receives all touches
because, by setting itself as the hit-test view, the superview
intercepts and receives touches that are normally passed to the
subview first. If a superview does not override hitTest:withEvent:,
touch events are associated with the subviews where they first
occurred and are never sent to the superview.
I have a simple piece of code in which i have overridden touchesBegan,Ended,Cancelled(empty block) and touchesMoved.
If i click ( i'm testing on Desktop PC ) with the mouse touchesBegan it's called, but touchesEnded is called only when i move finger for a while. That makes impossible to recognize a single tap or a drag of the finger, and handle them differently.
I don't understand if this is an emulator problem or i am misunderstanding the whole process. Did you have the same problem?
I have a simple solution for my application, like check a "first move" variable in touchesBegan, but this is a pure technical question.
Thank you in advance.
This is all i use, apart from drawRect that it's not important.
I guess it's not a problem in my code.
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let touch = touches.allObjects[0] as UITouch
let touchPoint = touch.locationInView(self)
println("touchesBegan")
if (Draw!){
path.moveToPoint(touchPoint)
path.addLineToPoint(touchPoint)
self.setNeedsDisplay()
}
}
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
let touch = touches.allObjects[0] as UITouch
let touchPoint = touch.locationInView(self)
println("touchesMoved")
if (Draw!){
path.addLineToPoint(touchPoint)
self.setNeedsDisplay()
}
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
let touch = touches.allObjects[0] as UITouch
let touchPoint = touch.locationInView(self)
println("touchesEnded")
if (Draw!){
path.addLineToPoint(touchPoint
path = UIBezierPath() // Create new path for next line
self.setNeedsDisplay()
}
}
I am quite sure this is an emulator problem.
Please see the code below. It works like a charm at my end.
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
didMove = false;
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
didMove = true;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if (didMove == true)
{
//finger was moved
NSLog(#"finger was moved");
}
else
{
//it's a tap
NSLog(#"finger not moved it's a tap");
}
}
While we are at it, can I bring your attention to UIGestureRecognizers? Try to use them since they make life a breeze.
I recently started working with sprite-kit. I know touchesBegan works for just one tap but is there something i can use that will recognize a touch being held down?
If you want to implement something like shooting then you need to start shooting in touchesBegan method and stop shooting in touchesEnded method:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self startShooting];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[self stopShooting];
}
For other purposes you can add UILongPressGestureRecognizer to the SKScene
Alternatively you can use a boolean with the update method:
bool isTouching = false;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
isTouching = true;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
isTouching = false;
}
-(void)update:(CFTimeInterval)currentTime {
if(isTouching){
//shooting!
}
}
You can easily combine method's of yours inside the isTouching block if you prefer, and use touchesBegan to lets say aim the bullets at the same time.
You don't need to worry about timers as the update method will keep executing the code block as long as isTouching == true
var isTouching = false
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
handleTouches(touches)
isTouching = true;
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
handleTouches(touches)
isTouching = false;
}
override func update(currentTime: NSTimeInterval) {
if isTouching{
//Shoot CODE!
}
}
I have a UISegmentedControl with 4 segments. When it is selected, it should maintain the selected state. When the same segment is clicked again, it should deselect itself.
How to achieve this?
Since UISegmentedControl only sends an action if a not selected segment is selected, you have to subclass UISegmentedControl to make a tiny change in its touch handling. I use this class:
#implementation MBSegmentedControl
// this sends a value changed event even if we reselect the currently selected segment
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSInteger current = self.selectedSegmentIndex;
[super touchesBegan:touches withEvent:event];
if (current == self.selectedSegmentIndex) {
[self sendActionsForControlEvents:UIControlEventValueChanged];
}
}
#end
Now you will get UIControlEventValueChanged events even if the segment is already selected. Simply save the current index in a variable and compare it in the action. If the two indexes match you have to unselect the touched segment.
// _selectedSegmentIndex is an instance variable of the view controller
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
_selectedSegmentIndex = self.segment.selectedSegmentIndex;
}
- (IBAction)segmentChanged:(UISegmentedControl *)sender {
if (sender.selectedSegmentIndex == _selectedSegmentIndex) {
NSLog(#"Segment %d deselected", sender.selectedSegmentIndex);
sender.selectedSegmentIndex = UISegmentedControlNoSegment;
_selectedSegmentIndex = UISegmentedControlNoSegment;
}
else {
NSLog(#"Segment %d selected", sender.selectedSegmentIndex);
_selectedSegmentIndex = sender.selectedSegmentIndex;
}
}
iOS 7 changed how touches are handled for UISegmentedControl. The selectedSegmentIndex is now changed during touchesEnded:.
So the updated Subclass should look like this:
#implementation MBSegmentedControl
+ (BOOL)isIOS7 {
static BOOL isIOS7 = NO;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSInteger deviceSystemMajorVersion = [[[[[UIDevice currentDevice] systemVersion] componentsSeparatedByString:#"."] objectAtIndex:0] integerValue];
if (deviceSystemMajorVersion >= 7) {
isIOS7 = YES;
}
else {
isIOS7 = NO;
}
});
return isIOS7;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSInteger previousSelectedSegmentIndex = self.selectedSegmentIndex;
[super touchesBegan:touches withEvent:event];
if (![[self class] isIOS7]) {
// before iOS7 the segment is selected in touchesBegan
if (previousSelectedSegmentIndex == self.selectedSegmentIndex) {
// if the selectedSegmentIndex before the selection process is equal to the selectedSegmentIndex
// after the selection process the superclass won't send a UIControlEventValueChanged event.
// So we have to do this ourselves.
[self sendActionsForControlEvents:UIControlEventValueChanged];
}
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
NSInteger previousSelectedSegmentIndex = self.selectedSegmentIndex;
[super touchesEnded:touches withEvent:event];
if ([[self class] isIOS7]) {
// on iOS7 the segment is selected in touchesEnded
if (previousSelectedSegmentIndex == self.selectedSegmentIndex) {
[self sendActionsForControlEvents:UIControlEventValueChanged];
}
}
}
#end
Swift 2.2 version, fixed the problem Grzegorz noticed.
class ReselectableSegmentedControl: UISegmentedControl {
#IBInspectable var allowReselection: Bool = true
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
let previousSelectedSegmentIndex = self.selectedSegmentIndex
super.touchesEnded(touches, withEvent: event)
if allowReselection && previousSelectedSegmentIndex == self.selectedSegmentIndex {
if let touch = touches.first {
let touchLocation = touch.locationInView(self)
if CGRectContainsPoint(bounds, touchLocation) {
self.sendActionsForControlEvents(.ValueChanged)
}
}
}
}
}
Swift 3.0 changes the fix for this to look like the following:
class MyDeselectableSegmentedControl: UISegmentedControl {
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
let previousIndex = selectedSegmentIndex
super.touchesEnded(touches, with: event)
if previousIndex == selectedSegmentIndex {
let touchLocation = touches.first!.location(in: self)
if bounds.contains(touchLocation) {
sendActions(for: .valueChanged)
}
}
}
}
Here is a fix for a problem that when you try to cancel selection by starting tap on UISegmentControl and later you finish touch outside - it still does deselection.
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint locationPoint = [[touches anyObject] locationInView:self];
CGPoint viewPoint = [self convertPoint:locationPoint fromView:self];
if ([self pointInside:viewPoint withEvent:event]) {
int oldValue = self.selectedSegmentIndex;
[super touchesEnded:touches withEvent:event];
if (oldValue == self.selectedSegmentIndex)
{
[super setSelectedSegmentIndex:UISegmentedControlNoSegment];
[self sendActionsForControlEvents:UIControlEventValueChanged];
}
}
}
You can do it with the following (thank you Grzegorz's answer and Matthias's answer):
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
NSInteger previousSelectedSegmentIndex = self.selectedSegmentIndex;
[super touchesEnded:touches withEvent:event];
CGPoint locationPoint = [[touches anyObject] locationInView:self];
CGPoint viewPoint = [self convertPoint:locationPoint fromView:self];
if ([self pointInside:viewPoint withEvent:event] && previousSelectedSegmentIndex == self.selectedSegmentIndex) {
self.selectedSegmentIndex = UISegmentedControlNoSegment;
[self sendActionsForControlEvents:UIControlEventValueChanged];
}
}
I have made an open-source (MIT Licensed) class STASegmentedControl (supports iOS 7+), that has this functionality baked in (and more).
In reference to the answer posted by #Matthias Bauch. I had to make little changes as per Swift 2.2 in Xcode 7.3:
class ReselectableSegmentedControl: UISegmentedControl {
#IBInspectable var allowReselection: Bool = true
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
let previousSelectedSegmentIndex = self.selectedSegmentIndex
super.touchesEnded(touches, withEvent: event)
if allowReselection && previousSelectedSegmentIndex == self.selectedSegmentIndex {
if let touch = touches.first {
let touchLocation = touch.locationInView(self)
if CGRectContainsPoint(bounds, touchLocation) {
self.sendActionsForControlEvents(.ValueChanged)
}
}
}
}
}
swift 3.1 version posted by #Kushal Ashok
class ReselectableSegmentedControl: UISegmentedControl {
#IBInspectable var allowReselection: Bool = true
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
let previousSelectedSegmentIndex = self.selectedSegmentIndex
super.touchesEnded(touches, with: event)
if allowReselection && previousSelectedSegmentIndex == self.selectedSegmentIndex {
if let touch = touches.first {
let touchLocation = touch.location(in: self)
if bounds.contains(touchLocation) {
self.sendActions(for: .valueChanged)
}
}
}
}
}
Here is a solution wich is independent from IOS Version. It's choosing the behaviour itself.
#interface CustomSegmentedControl : UISegmentedControl
#end
#implementation CustomSegmentedControl{
BOOL _touchBegan;
BOOL _reactOnTouchBegan;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
_touchBegan = YES;
NSInteger previousSelectedSegmentIndex = self.selectedSegmentIndex;
[super touchesBegan:touches withEvent:event];
if (_reactOnTouchBegan) {
// before iOS7 the segment is selected in touchesBegan
if (previousSelectedSegmentIndex == self.selectedSegmentIndex) {
[self sendActionsForControlEvents:UIControlEventValueChanged];
}
}
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
_touchBegan = NO;
NSInteger previousSelectedSegmentIndex = self.selectedSegmentIndex;
[super touchesEnded:touches withEvent:event];
if (!_reactOnTouchBegan) {
CGPoint locationPoint = [[touches anyObject] locationInView:self];
CGPoint viewPoint = [self convertPoint:locationPoint fromView:self];
if ([self pointInside:viewPoint withEvent:event]) {
// on iOS7 the segment is selected in touchesEnded
if (previousSelectedSegmentIndex == self.selectedSegmentIndex) {
[self sendActionsForControlEvents:UIControlEventValueChanged];
}
}
}
}
- (void)sendActionsForControlEvents:(UIControlEvents)controlEvents {
if(controlEvents == UIControlEventValueChanged){
_reactOnTouchBegan = _touchBegan;
}
[super sendActionsForControlEvents:controlEvents];
}
#end
Very helpful! Thank you! I wanted a little more control over the events for my project, so I adapted #Matthias's answer to send a custom "Value unchanged" event. I put an example on GitHub.
I also incorporated #Grzegorz's fix so it behaves properly if the user drags her finger outside the segmented control.
In reference to #Stunner, this is my contribution to achieve the goal. I changed something and added the property _previousSelectedSegmentIndex; in the #Stunner code the variable previousSelectedSegmentIndex was useless:
#implementation STASegmentedControl
{
NSInteger _previousSelectedSegmentIndex;
}
- (void)setSelectedSegmentIndex:(NSInteger)selectedSegmentIndex
{
[super setSelectedSegmentIndex: selectedSegmentIndex];
_previousSelectedSegmentIndex = self.selectedSegmentIndex;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesEnded:touches withEvent:event];
CGPoint locationPoint = [[touches anyObject] locationInView:self];
CGPoint viewPoint = [self convertPoint:locationPoint fromView:self];
if (self.toggleableSegments) { // toggle selected segment on/off
if ([self pointInside:viewPoint withEvent:event] && _previousSelectedSegmentIndex == self.selectedSegmentIndex) {
self.selectedSegmentIndex = UISegmentedControlNoSegment;
[self sendActionsForControlEvents:UIControlEventValueChanged];
}
}
_previousSelectedSegmentIndex = self.selectedSegmentIndex;
}
I am trying to limit the swipe area of the UIScrollview, but i amnot able to do that.
I would like to set the swipe area only to the top of the UIScrollview, but i would like to set all the content visible.
Update:
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if ([touches count] > 0) {
UITouch *tempTouch = [touches anyObject];
CGPoint touchLocation = [tempTouch locationInView:self.categoryScrollView];
if (touchLocation.y > 280.0)
{
NSLog(#"enabled");
self.categoryScrollView.scrollEnabled = YES;
}
}
[self.categoryScrollView touchesBegan:touches withEvent:event];
}
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
// [super touchesEnded:touches withEvent:event];
self.categoryScrollView.scrollEnabled = YES;
[self.categoryScrollView touchesBegan:touches withEvent:event];
}
Solution:
dont forget to set delaysContentTouches to NO on the UIScrollView
self.categoryScrollView.delaysContentTouches = NO;
You can disable scrolling on the UIScrollView, override touchesBegan:withEvent: in your view controller, check if any of the touches began in the area where you'd like to enable swipes, and if the answer is 'yes', re-enable scrolling. Also override touchesEnded:withEvent: and touchesCancelled:withEvent: to disable scrolling when the touches are over.
Other answers didn't work for me. Subclassing UIScrollView worked for me (Swift 3):
class ScrollViewWithLimitedPan : UIScrollView {
// MARK: - UIPanGestureRecognizer Delegate Method Override -
override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
let locationInView = gestureRecognizer.location(in: self)
print("where are we \(locationInView.y)")
return locationInView.y > 400
}
}
This blog post showcases a very simple and clean way of implementing the functionality.
// init or viewDidLoad
UIScrollView *scrollView = (UIScrollView *)view;
_scrollViewPanGestureRecognzier = [[UIPanGestureRecognizer alloc] init];
_scrollViewPanGestureRecognzier.delegate = self;
[scrollView addGestureRecognizer:_scrollViewPanGestureRecognzier];
//
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer*)otherGestureRecognizer
{
return NO;
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
if (gestureRecognizer == _scrollViewPanGestureRecognzier)
{
CGPoint locationInView = [gestureRecognizer locationInView:self.view];
if (locationInView.y > SOME_VALUE)
{
return YES;
}
return NO;
}
return NO;
}