将手势识别器添加到UISlider最小/最大值图像

时间:2013-10-16 02:45:13

标签: iphone ios uiimage uigesturerecognizer uislider

我需要为UISlider的最小值和最大值图像添加触摸响应。滑块是一个缩放栏,因此图像是减号和加号,如果触摸,它们应相应地放大或缩小。 UISlider属性minimumValueImagemaximumValueImage的类型为UIImage,而不是UIImageView,因此我无法直接向其添加手势识别器。

有什么想法吗?唯一的选择是获得hacky并在图像上方制作清晰的按钮?如果是这种情况,我怎样才能获得最小/最大图像帧?

3 个答案:

答案 0 :(得分:0)

您要查找的图片视图位于 UISlider 类中的@package内,无法从外部访问

UIImageView *_minValueImageView;
UIImageView *_maxValueImageView;

您仍然可以使用Objective c runtime来获取它们。

#import <objc/runtime.h>

// Initialize slider and images
UISlider *slider = [[UISlider alloc] initWithFrame:CGRectMake(100, 100, 300, 40)];
[slider setMinimumValueImage:[UIImage imageNamed:@"img1"]];
[slider setMaximumValueImage:[UIImage imageNamed:@"img2"]];

Ivar minimumValueImageViewIvar = class_getInstanceVariable([slider class], "_minValueImageView");
UIImageView *minimumValueImageView =  (UIImageView*)( object_getIvar(slider, minimumValueImageViewIvar) );
// [minimumValueImageView setHidden:YES];

Ivar maximumValueImageViewIvar = class_getInstanceVariable([slider class], "_maxValueImageView");
UIImageView *maximumValueImageView =  (UIImageView*)( object_getIvar(slider, maximumValueImageViewIvar) );
// [maximumValueImageView setHidden:YES];

答案 1 :(得分:0)

您可以查看滑块的子视图。应该有2个UIImageView。然后,您可以设置userInteractionEnabled = YES并为每个人添加UITapGestureRecognizer。

NSMutableArray* images = [NSMutableArray array];
for (id sv in slider.subviews) {
   if ([sv isKindOfClass:[UIImageView class]]) {
       [image addObject:sv];
   }
}
if (images.count == 2) {
    UITapGestureRecognizer* gr = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                         action:@selector(minImageTapped:)];
    [imageViews[0] addGestureRecognizer:gr];
    [imageViews[0] setUserInteractionEnabled:YES];

    gr = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                 action:@selector(maxImageTapped:)];
    [imageViews[1] addGestureRecognizer:gr];
    [imageViews[1] setUserInteractionEnabled:YES];
}

答案 2 :(得分:0)

GenesisST的答案的快速版本:

let images:[UIView] = outsSlider.subviews.filter({$0 is UIImageView})

if (images.count == 2) {
    let tapMin = UITapGestureRecognizer(target: self, action: #selector(minImageTapped));
    let tapMax = UITapGestureRecognizer(target: self, action: #selector(maxImageTapped));
    images[0].addGestureRecognizer(tapMin)
    images[1].addGestureRecognizer(tapMax)
    images[0].isUserInteractionEnabled = true
    images[1].isUserInteractionEnabled = true
}