gpt4 book ai didi

iphone - 非常简单的自定义 UIView,drawRect 没有被调用

转载 作者:行者123 更新时间:2023-11-29 11:21:10 27 4
gpt4 key购买 nike

我有这个 super 简单的例子,但我不确定它为什么不起作用。 drawRect 永远不会被调用。我只想画一个正方形并且是红色的。我做错了什么?

//Controller.h

#import <Foundation/Foundation.h>
@class CustomView;

@interface Controller : NSObject
@property (nonatomic, retain) CustomView *cv;
@end

//Controller.m
#import "Controller.h"
#import "CustomView.h"

@implementation Controller
@synthesize cv;

- (void) awakeFromNib {
NSLog(@"awakeFromNib called");

CGRect theFrame = CGRectMake(20, 20, 100, 100);
cv = [[CustomView alloc] initWithFrame:theFrame];

UIWindow *theWindow = [[UIApplication sharedApplication] keyWindow];
[theWindow addSubview:cv];
[cv setNeedsDisplay];
}
@end

//CustomView.h
#import <UIKit/UIKit.h>
@interface CustomView : UIView
@end

//CustomView.m
#import "CustomView.h"

@implementation CustomView

- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
NSLog(@"initWithFrame called");
}
return self;
}

- (void)drawRect:(CGRect)rect {
NSLog(@"drawRect called");
self.backgroundColor = [UIColor redColor];
}
@end

最佳答案

您没有在 drawRect 中绘制任何东西。您只是在 View 上设置一个属性。如果您覆盖了 drawRect,则不会绘制任何内容 - 尝试调用 [super drawRect:rect](在设置背景颜色后)或简单地使用以下方法自己绘制正方形:

[[UIColor redColor] set];    
[[UIBezierPath bezierPathWithRect:self.bounds] fill];

编辑:

我看到你的 drawRect 甚至没有被调用。我不确定你的 Nib 结构,但尝试在你的 Controller 中将 cv 作为 subview 添加到 self.view 而不是将它添加到窗口。另外,请注意您没有保留 cv(使用 self.cv = 而不是 cv =)但这应该不是问题,因为您的 View 将保留它。

关于iphone - 非常简单的自定义 UIView,drawRect 没有被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7067395/

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