UISlider 制作的声音显示效果

简单地演示效果,直接在入口类实现

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    // Override point for customization after application launch.

    self.window.backgroundColor = [UIColor whiteColor];

    [self.window makeKeyAndVisible];

    

    UISlider *slider = [[UISlider alloc] init];

    slider.center = CGPointMake(160, 400);

    slider.bounds = CGRectMake(0, 0, 240, 20);

    slider.tag = 100;

    slider.minimumValue = 0;

    slider.maximumValue = 100;

    slider.minimumTrackTintColor = [UIColor greenColor]; //已经滑过的颜色

    slider.maximumTrackTintColor = [UIColor blueColor];//滑动条的颜色

    slider.value = 30;

    [slider addTarget:self action:@selector(changeVoice:) forControlEvents:UIControlEventValueChanged];

    [self.window addSubview:slider];

    

    _imageView = [[UIImageView alloc] init];

    _imageView.center = CGPointMake(20, 400);

    _imageView.bounds = CGRectMake(0, 0, 20, 20);

    _imageView.image = [UIImage imageNamed:@"mid.png"];

    [self.window addSubview:_imageView];

    

//    [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(addValue:) userInfo:slider repeats:YES];

    

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];

    btn.frame = CGRectMake(0, 0, 20, 20);

    [_imageView addSubview:btn];

    _imageView.userInteractionEnabled = YES;

    [btn addTarget:self action:@selector(voiceChange) forControlEvents:UIControlEventTouchUpInside];

    return YES;

}



//定时器方法,声音自动提高,但这时虽然滑动条的值发生变化,但是并不触发方法

- (void)addValue:(NSTimer *)timer

{

    UISlider *slider = (UISlider *)[timer userInfo];

    if (slider.value < 30)

    {

        slider.value += 0.1;

    }

}



//声音的高低可又图标表示出来

- (void)changeVoice:(UISlider *)slider

{

    if (slider.value == 0)

    {

        _imageView.image = [UIImage imageNamed:@"none.png"];

        return;

    }

    if (slider.value < 30)

    {

        _imageView.image = [UIImage imageNamed:@"low.png"];

        return;

    }

    if (slider.value < 60)

    {

        _imageView.image = [UIImage imageNamed:@"mid.png"];

        return;

    }

    if (slider.value <= 100)

    {

        _imageView.image = [UIImage imageNamed:@"high.png"];

    }

}



//当声音不为 0 的时候,点击声音图标总是将声音置 0,当再次点击图标的时候,声音恢复

- (void)voiceChange

{

    UISlider *slider = (UISlider *)[self.window viewWithTag:100];

    static int count = 0;

    count ++;

    if (count % 2 != 0)

    {

        _voiceValue = slider.value;  //记住上次的声音

        slider.value = 0;

    }

    else

    {

        if (slider.value != 0) //在回复声音之前已经将声音调节不再为0,则使用递归

        {

            [self voiceChange];

            count = 0;

        }

        slider.value = _voiceValue;

    }

}



@end

代码中的定时器本来是像模拟一下让声音自动提升的效果,演示的时候才知道这样并不可以,想了想,滑动条应该是需要与用户交互才能显示它存在的意义。

 

你可能感兴趣的:(slider)