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

问题描述:

为了绘制每秒更改位置的线,我划分了UIView子类。我正在使用NSTimer调用setNeedsDisplay以更新视图,但结果不正确。它正在绘制新旧线条。这里是我的LineView.h/M代码:使用NSTimer重绘UIView无法按预期方式工作

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或xibs。如果我将故事板中的视图子类化并为其创建插座,则视图会正确更新,但我想避免触摸故事板。

+0

@rmaddy不会做任何事情。 [根据Apple文档](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/index.html#//apple_ref/occ/instm/UIView/drawRect :),“*这个方法的默认实现什么也不做,使用Core Graphics和UIKit等技术绘制其视图内容的子类应该重写此方法并在其中实现它们的绘图代码。*“ – Hamish

+0

@ originaluser2是的。我刚刚回顾了一些我的代码,没有一个我的'drawRect:'方法调用'[super drawRect:]'。没关系。 – rmaddy

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

试试这个。我已经用它做好了你的项目。

+0

你可以设置你背景冷到任何我设置为黑色。 –

+0

谢谢。它现在有效。 – hullabal00

+0

还请看到uiview的opaque和clearContextBeforeDrawing属性的文档。 –