我对 iPhone 开发还很陌生,我正在构建我的第一个应用程序:)
在我的一个视图控制器中,我构建了一个 customSlider,它应该充当本机“滑动解锁”滑块。
我现在的疑问是如何实现“拖到外面”的行为。如前所述,我希望它与本机滑块完全相同,这意味着当手指拖动滑块时,如果它移出滑块,滑块应该为零。
我的疑问不是动画部分(我已经成功使用动画块),而是控制事件部分。我应该使用哪个控制事件?
我在用着:
[customSlider addTarget:self action:@selector(sliderMoved:) forControlEvents:UIControlEventValueChanged];
处理滑动部分(手指滑动光标),以及
[customSlider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventTouchUpInside];
处理释放部分,但问题是,如果我在外面释放手指,则不会调用 sliderAction 函数。
编辑:
我试图实现 @Bruno Domingues 给我的解决方案,但我意识到问题是默认情况下 UISlider 会不断更新,即使手指被拖动到它之外(尝试打开例如系统中的亮度部分)首选项,您会看到滑块将继续更新,即使您将其拖动到其外部)。所以我的问题可以重新定义:如何避免这种默认行为并仅当手指在滑块上移动时才更新滑块?
只需中断自定义子类中的触摸方法,然后仅将您想要执行的触摸转发到超类,如下所示:
in .h:
@interface CustomSlider : UISlider
@end
in .m:
#import "CustomSlider.h"
@implementation CustomSlider
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
CGPoint touchLocation = [[touches anyObject] locationInView:self];
if (touchLocation.x < 0 || touchLocation.y<0)return;
if (touchLocation.x > self.bounds.size.width || touchLocation.y > self.bounds.size.height)return;
[super touchesBegan:touches withEvent:event];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
CGPoint touchLocation = [[touches anyObject] locationInView:self];
if (touchLocation.x < 0 || touchLocation.y<0)return;
if (touchLocation.x > self.bounds.size.width || touchLocation.y > self.bounds.size.height)return;
[super touchesMoved:touches withEvent:event];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
CGPoint touchLocation = [[touches anyObject] locationInView:self];
if (touchLocation.x < 0 || touchLocation.y<0)return;
if (touchLocation.x > self.bounds.size.width || touchLocation.y > self.bounds.size.height)return;
[super touchesEnded:touches withEvent:event];
}
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{
CGPoint touchLocation = [[touches anyObject] locationInView:self];
if (touchLocation.x < 0 || touchLocation.y<0)return;
if (touchLocation.x > self.bounds.size.width || touchLocation.y > self.bounds.size.height)return;
[super touchesCancelled:touches withEvent:event];
}
@end
请注意,如果您的手指移回控件,此实现将开始更新控件。为了消除这种情况,如果在视图之外接收到触摸,只需设置一个标志,然后在后续触摸方法中检查该标志。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)