在子视图中读取UISlider值?

时间:2014-09-03 10:44:47

标签: ios objective-c

如何在SubView中读取UISlider的值?我尝试了以下但是我在UIView类型的对象上得到了错误属性“找不到滑块”?提前致谢。

#import "ViewController.h"

@interface ViewController ()
@property UIView *controlview;
@property UISlider *slider;

@end


@implementation ViewController

- (void)viewDidLoad
{
   [super viewDidLoad];
    self.view.backgroundColor = [UIColor redColor];
    UIView *controlview = [[UIView alloc]initWithFrame:CGRectMake(0, 100,                 self.view.frame.size.width, (self.view.frame.size.height/4))];
    controlview.backgroundColor = [UIColor blackColor];
   [self.view addSubview:controlview];
   CGRect frame = CGRectMake(0.0, 0.0, 100.0, 40.0);
    UISlider *slider = [[UISlider alloc] initWithFrame:frame];
   [slider addTarget:self action:@selector(sliderAction) forControlEvents:UIControlEventValueChanged];
    slider.minimumValue = 0.0;
    slider.maximumValue = 50.0;
    slider.continuous = YES;
    slider.value = 25.0;
    [controlview addSubview:slider];
 }

 - (void)sliderAction 
 {
    float slidervalue = [_controlview.slider.value];
    self.view.frame = CGRectMake(slidervalue, 0, self.view.frame.size.width, 480);
    NSLog(@"YES");
 }

@end

2 个答案:

答案 0 :(得分:0)

滑块是您班级的属性,只需通过调用self.slider.value来读取它的值:

float slidervalue = self.slider.value;

同样改变这个:

UISlider *slider = [[UISlider alloc] initWithFrame:frame];

到此:

self.slider = [[UISlider alloc] initWithFrame:frame];

答案 1 :(得分:0)

您在代码中创建了两个无用的属性,因为您在本地添加了对象。

Problem 因为滑块是代码中的本地对象。您无法在定义的方法之外访问滑块对象。

Solution 在代码中更改此行

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

并改变方法

- (void)sliderAction:(id)sender
{
   UISlider *mySlider = (UISlider*)sender; 
   float slidervalue = mySlider.value;
   self.view.frame = CGRectMake(slidervalue, 0, self.view.frame.size.width, 480);
}