gpt4 book ai didi

ios - setNeedsDisplay 未调用drawRect

转载 作者:行者123 更新时间:2023-11-29 03:03:07 25 4
gpt4 key购买 nike

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

自定义 View .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

谢谢

最佳答案

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

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

@property (weak,nonatomic) IBOutlet CustomView *cv;

@end

然后,在 Storyboard中,将 ViewController 的 cv socket 连接到 CustomView。此外,您还需要在 CustomView 上实现 initFromCoder: 方法。

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

关于ios - setNeedsDisplay 未调用drawRect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23087271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com