【问题标题】:drawRect not getting called from setNeedsDisplay没有从 setNeedsDisplay 调用 drawRect
【发布时间】:2014-04-15 14:51:19
【问题描述】:

我最近开始学习在视图上绘制核心图形,但是每次调用setNeedsDisplay 时,方法都会运行但不会触发drawRect。在我的项目中,我在视图控制器上有一个视图。该视图包含drawRect 中的 if 语句,用于检查 BOOL 变量是 YES 还是 NO。如果是,它使用代码绘制一个红色圆圈。如果否,则绘制一个蓝色圆圈。在 BOOL 的设置器中,它调用 setNeedsDisplay。我在 ViewController 中创建了这个视图类的一个实例并设置了 BOOL 但视图没有重绘。为什么没有调用该方法?我在下面发布了 xcode 文件和代码位。

Customview.m:

    #import "CustomView.h"

@implementation CustomView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}

-(void)awakeFromNib{
    [self setup];
}

-(void)setup{
    _choice1 = YES;
}

-(void)setChoice1:(BOOL)choice1{
    _choice1 = choice1;
    [self setNeedsDisplay];
}


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    if (_choice1) {
        UIBezierPath * redCircle = [UIBezierPath bezierPathWithOvalInRect:rect];
        [[UIColor redColor]setFill];
        [redCircle fill];
    }else if (!_choice1){
        UIBezierPath * blueCircle = [UIBezierPath bezierPathWithOvalInRect:rect];
        [[UIColor blueColor]setFill];
        [blueCircle fill];

    }
}

@end

CustomView.h:

    #import <UIKit/UIKit.h>

@interface CustomView : UIView

@property (nonatomic) BOOL choice1;

@end

ViewController.m:

#import "ViewController.h"
#import "CustomView.h"

@interface ViewController ()
- (IBAction)Change:(id)sender;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)Change:(id)sender {
    CustomView * cv = [[CustomView alloc]init];
    [cv setChoice1:NO];
}
@end

完整项目:https://www.mediafire.com/?2c8e5uay00wci0c

谢谢

【问题讨论】:

    标签: ios objective-c core-graphics drawrect setneedsdisplay


    【解决方案1】:

    您需要在您的ViewController 中为您的CustomView 创建一个出口。删除创建新CustomView 实例的代码,使用_cv 引用customView。

    @interface ViewController ()
    - (IBAction)Change:(id)sender;
    
    @property (weak,nonatomic) IBOutlet CustomView *cv;
    
    @end
    

    然后,在情节提要中,将 ViewController 的 cv 出口连接到 CustomView。此外,您还需要在CustomView 上实现initFromCoder: 方法。

    - (id)initWithCoder:(NSCoder *)aDecoder {
        if ((self = [super initWithCoder:aDecoder])) {
            [self setup];
        }
        return self;
    }
    

    【讨论】:

    • 我在情节提要中添加了视图并设置了自定义类。如何仅在该类的实例上调用方法?
    • 在您的Change: 方法中,您正在创建一个新实例,因此它不会附加到情节提要实例。相反,您需要将情节提要实例连接到您的视图控制器。我会更新我的答案。
    • 完美!有效!非常感谢,因为我没有足够的积分,所以无法投票。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多