how can I change the default values for UISlider in a custom subclass of UISlider so I can reuse it multiple times

StackOverflow https://stackoverflow.com/questions/21813884

  •  12-10-2022
  •  | 
  •  

Domanda

At the moment I'm subclassing a UISlider and in the drawRect setting the default values. I'm getting a strange result.

The slider min image is at the correct position but the slider max image has white space on the left. The slider image in the middle is to far right and the colour for maximumTackTintColor is on both sides of the slider.

- (void)drawRect:(CGRect)rect
{
    // Drawing code
    self.minimumTrackTintColor = [ThemeManager minimumTrackTintColorForSlider];
    self.maximumTrackTintColor = [ThemeManager maximumTrackTintColorForSlider];
    self.minimumValueImage = [UIImage imageNamed:@"sliderLeftDot"];
    self.maximumValueImage = [UIImage imageNamed:@"sliderRightDot"];

    [self setThumbImage:[UIImage imageNamed:@"sliderCentrePiece"] forState:UIControlStateNormal];

}
È stato utile?

Soluzione

You're not calling [super drawRect:rect] and this causes the slide to never be drawn properly, however you should never override drawRect: unless you need to perform custom drawing.

The right place where to initialize defaults is the designated initializer(s). Being UISlider a subclass of UIView, you need to override both -initWithFrame: and -initWithCoder:, to handle both the cases in which the slider is created programmatically or via a nib.

For instance

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self commonInit];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit {
    self.minimumTrackTintColor = [ThemeManager minimumTrackTintColorForSlider];
    self.maximumTrackTintColor = [ThemeManager maximumTrackTintColorForSlider];
    self.minimumValueImage = [UIImage imageNamed:@"sliderLeftDot"];
    self.maximumValueImage = [UIImage imageNamed:@"sliderRightDot"];
    [self setThumbImage:[UIImage imageNamed:@"sliderCentrePiece"] forState:UIControlStateNormal];
}

Altri suggerimenti

Do not put that code in the drawRect: method. Put it in the appropriate init method or put it in another method that you call when you want the slider customized.

Even better is to make used of the UIAppearance feature to set the tint colors for all sliders:

[[UISlider appearance] setMinimumTrackTintColor:someColor];
[[UISlider appearance] setMaximumTrackTintColor:someColor];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top