UISlider setMaximumTrackTintColor

前端 未结 6 904
情书的邮戳
情书的邮戳 2021-01-01 22:34

I\'m trying to dynamically configure the track color on a UISlider.

This line of code works perfectly for setting the low side of the slider track.

[

6条回答
  •  时光取名叫无心
    2021-01-01 22:55

    For me the problem occurred because I had subclassed UISlider to create a custom trackRectForBounds that was returning a CGRect with an invalid size. My original implementation (and maybe some iOS version's implementations?) returned a track bounds with a zero or negative size depending on the UISlider's bounds. It appears that it is related to the fact that setting minimum/maximumTrackTintColor will call trackRectForBounds, possibly in order to create a track image.

    The fix to the problem is making sure that the track bounds will be valid when setting minimum/maximum track tint colors.

    Option 1: use initWithFrame that is sufficiently sized for the UISlider

    UISlider *slider = [[UISlider alloc] initWithFrame:CGRectMake(0,0,100,38)];
    slider.minimumTrackTintColor = [UIColor greenColor];
    slider.maximumTrackTintColor = [UIColor orangeColor];
    // ... rest of view setup ...
    

    Option 2: add the slider and force auto-layout so that it is correctly sized before setting the tint colors

    UISlider *slider = [[UISlider alloc] init]; // <-- problem, zero size
    [view addSubview:slider];
    // ... other view setup, including constraints ...
    [view layoutIfNeeded]; // forced layout to give slider a non-zero size
    slider.minimumTrackTintColor = [UIColor greenColor];
    slider.maximumTrackTintColor = [UIColor orangeColor];
    

    Option 3: fix the override to make sure that it will return a rectangle of non-zero size, regardless of bounds.

    - (CGRect)trackRectForBounds:(CGRect)bounds {
         // example, inset left/right by 2 (thus width - 4)
         // track height is 5 pixels, centered in bounds.
         return CGRectMake(
             CGRectGetMinX(bounds) + 2,
             CGRectGetMinY(bounds) + (CGRectGetHeight(bounds) + 5)/2.0,
             MAX(10, CGRectGetWidth(bounds) - 4), // use max make sure positive.
             5)
    }
    

    Note: I am creating UISliders after the viewDidLoad so Ahufford's answer wouldn't work for me, but I presume this could also explain it. I would also guess Ahufford's answer will probably work best in most cases.

提交回复
热议问题