【问题标题】:How to read size of UISlider thumb image如何读取 UISlider 拇指图像的大小
【发布时间】:2014-01-23 16:22:55
【问题描述】:

我正在尝试在 UISlider 的拇指上方居中放置一个额外的 UIView。为此,我需要拇指图像的宽度。在 iOS6 中,这工作正常。我可以使用:

CGFloat thumbWidth = self.navSlider.currentThumbImage.size.width;

(如本答案所示:How to get the center of the thumb image of UISlider

这在 iOS7 中返回 0.0f。我也尝试过使用:

UIImage *thumb = [self.navSlider thumbImageForState:UIControlStateNormal];

但拇指最终为零。

是否可以读取默认滑块缩略图的大小?还是我必须找到它,设置一个常量,Apple 以后如何不更改它?

【问题讨论】:

    标签: ios iphone uislider


    【解决方案1】:

    currentThumbImage 属性上的文档说:

    如果没有使用 setThumbImage:forState: 方法,该属性包含值 nil。 在这种情况下,接收器使用默认拇指图像 绘图。

    thumbImageForState: 上的文档不太清楚:

    返回值与指定状态关联的缩略图,或 如果无法检索到合适的图像,则为零。

    我认为您在尝试找出默认拇指大小时可能会不走运。安装一个看起来与系统图像完全一样的“自定义”拇指图像怎么样?这将解决 Apple 将其从您的下方换掉的问题。

    【讨论】:

    • 我希望在没有自定义图像的情况下执行此操作,但我认为这可能是唯一的方法。至少它在整个操作系统中看起来是一致的。谢谢!
    【解决方案2】:

    我在我的子类中使用它:

    CGRect trackRect = [self trackRectForBounds:self.bounds];
    CGRect thumbRect = [self thumbRectForBounds:self.bounds trackRect:trackRect value:0];
    CGSize thumbSize = thumbRect.size;
    

    【讨论】:

    • 聪明的答案。但是,我们仍然可以在没有子类的情况下获得拇指的大小或矩形: ` 使用slider?.superview.convertRect(thumbRect, fromView: slider) 在superview的坐标中使用它。
    • 太棒了!
    【解决方案3】:

    您需要使用 setThumbImage forState 设置初始拇指图像。这在 iOS7 中对我来说很好,并返回图像的正确宽度。滑块设置在故事板中并通过 IBOutlet 连接。

    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        [self.slider setThumbImage:[UIImage imageNamed:@"tick.jpg"] forState:UIControlStateNormal];
    
        float check = self.slider.currentThumbImage.size.width;
        NSLog(@"Check is %f", check);
    
    }
    

    【讨论】:

    • 我希望在不为滑块提供自定义图像的情况下做到这一点。不过,这可能是让它发挥作用的唯一方法。
    【解决方案4】:

    如果布局流程尚未完成,我相信这有时会返回 0。我遇到了一些麻烦。

    CGRect thumbRect = [self thumbRectForBounds:self.bounds
                                      trackRect:[self trackRectForBounds:self.bounds]
                                          value:self.value];
    CGFloat thumbDiameter = CGRectGetHeight(thumbRect);
    

    【讨论】:

      【解决方案5】:

      这是另一个可行的方法,但它比第一个更“hackier”,并假设默认拇指图像宽度在未来版本的 iOS(过去 11 版)中不会改变

      - (CGFloat)thumbImageWidth // default thumb image is 30 px,
      {
          double imgThumbImageWidth = self.currentThumbImage.size.width;
          if (imgThumbImageWidth && imgThumbImageWidth != 0 && imgThumbImageWidth != thumbImageWidth) {
              thumbImageWidth = imgThumbImageWidth;
          }
          else if (!thumbImageWidth || thumbImageWidth == 0) { // No custom image set, use 30
              thumbImageWidth = 31;
          }
          return thumbImageWidth;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多