使用NSTimer重绘UIView无法按预期工作

时间:2016-02-06 21:07:44

标签: ios objective-c uiview nstimer drawrect

我将UIView子类化,以便绘制一条每秒更改位置的行。我使用NSTimer来调用setNeedsDisplay以更新视图,但结果不正确。它正在绘制旧的和新的线条。这是我的LineView.h / m代码:

LineView.h:

@interface LineView : UIView
@property(nonatomic, assign) int length;
@end

LineView.m:

#import "LineView.h"
@implementation LineView
- (void)setLength:(int)length {
    _length = length;
    [self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect {    
    UIBezierPath *line = [UIBezierPath bezierPath];
    [line moveToPoint:CGPointMake(10, 10)];
    [line addLineToPoint:CGPointMake(100, 100+_length)];
    line.lineWidth = 10;
    [[UIColor blueColor] setStroke];
    [line stroke];
}
@end

在我的ViewController.m文件中,在viewDidLoad中,我初始化lineView并启动计时器:

- (void)viewDidLoad {
    [super viewDidLoad];
    _length = 100;

    _lineView = [[LineView alloc]initWithFrame:self.view.bounds];
    _lineView.length = _length;
    [self.view addSubview:_lineView];

    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime:) userInfo:nil repeats:true];
}

- (void)updateTime:(NSTimer*)timer {
    _length += 20;
    self.lineView.length = _length;
}

我想以编程方式执行此操作,而不是使用storyboard或xib。如果我在storyboard中继承视图并为其创建一个插座,那么视图会正确更新,但我想避免触及故事板。

1 个答案:

答案 0 :(得分:0)

_lineView.opaque = NO;
_lineView.backgroundColor = [UIColor blackColor];

试试这个。我用它来运行你的项目它做得很好。