2013-05-22 63 views
1

我想根據UISlider的值移動在UIView中繪製的點。下面的代碼是在UIViewController上使用自定義類(WindowView)的UIView(子視圖?)。在drawRect中獲取UISlider的當前值:方法

WindowView.h

#import <UIKit/UIKit.h> 

@interface WindowView : UIView 

- (IBAction)sliderValue:(UISlider *)sender; 

@property (weak, nonatomic) IBOutlet UILabel *windowLabel; 


@end 

WindowView.m

#import "WindowView.h" 

@interface WindowView() 
{ 
    float myVal; // I thought my solution was using an iVar but I think I am wrong 
} 

@end 

@implementation WindowView 

@synthesize windowLabel; 
- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     // Initialization code 
    } 
    return self; 
} 

- (void)sliderValue:(UISlider *)sender 
{ 
    myVal = sender.value; 
    windowLabel.text = [NSString stringWithFormat:@"%f", myVal]; 
} 

- (void)drawRect:(CGRect)rect 
{ 
    // I need to get the current value of the slider in drawRect: and update the position of the circle as the slider moves 
    UIBezierPath *circle = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(myVal, myVal, 10, 10)]; 
    [circle fill]; 
} 

@end 

回答

1

OK,你需要將滑塊值存儲在一個實例變量,然後強制視圖重繪。

WindowView.h:

#import <UIKit/UIKit.h> 

@interface WindowView : UIView 
{ 
    float _sliderValue; // Current value of the slider 
} 

// This should be called sliderValueChanged 
- (IBAction)sliderValue:(UISlider *)sender; 

@property (weak, nonatomic) IBOutlet UILabel *windowLabel; 
@end 

WindowView.m(僅在修改方法):

// This should be called sliderValueChanged 
- (void)sliderValue:(UISlider *)sender 
{ 
    _sliderValue = sender.value; 
    [self setNeedsDisplay]; // Force redraw 
} 

- (void)drawRect:(CGRect)rect 
{ 
    UIBezierPath *circle = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(_sliderValue, _sliderValue, 10, 10)]; 
    [circle fill]; 
} 

你可能想初始化_sliderValue的東西在視圖中的init方法有用。

_sliderValue可能不是你想要選擇的名稱;或許像_circleOffset或其他一些類似的東西。

+0

甜!我知道這很簡單。感謝十億! –

相關問題