在drawRect:方法中获取UISlider的当前值
Posted
技术标签:
【中文标题】在drawRect:方法中获取UISlider的当前值【英文标题】:Get the current value of UISlider in drawRect: method 【发布时间】:2013-05-22 00:46:02 【问题描述】:我正在尝试根据 UISlider 的值移动在 UIView 中绘制的点。下面的代码适用于在 UIViewController 上具有自定义类 (WindowView) 的 UIView(子视图?)。
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】:好的,您需要将滑块值存储在实例变量中,然后强制视图重绘。
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
之类的。
【讨论】:
甜蜜!我知道这很简单。谢谢十亿!以上是关于在drawRect:方法中获取UISlider的当前值的主要内容,如果未能解决你的问题,请参考以下文章
调整 UIView 的大小,但 drawRect 完成的绘图也会改变大小
如何在单个@IBAction 中获取多个 UISlider 的值?