【问题标题】:drawRect being called but the code within it not being executed when run?drawRect 被调用但其中的代码在运行时没有被执行?
【发布时间】:2013-05-05 00:43:40
【问题描述】:

我从 XCODE 4.5.2 中选择了单视图应用程序模板。我有一个 appdelegate ,一个带有 RDViewController.xib 的视图控制器,我已经制作了我的 UIView 类 Graphics 的类型。我也有 Graphics.h 和 Graphics.m(其中的 drawRect 方法)。 viewController.m 中有一个 Graphics 类类型的 graphics 属性。运行时调用 drawRect 方法,但在模拟器上没有绘制任何内容。未调用 Graphics 类中的 initWithFrame 方法。 RDViewController.xib 是 Graphics 的子类。

在 appdelegate 中:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.viewController = [[RDViewController alloc] initWithNibName:@"RDViewController" bundle:nil];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

我只在一个 ViewController 中编写过:

@implementation RDViewController

@synthesize graphics;

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

    [self.graphics setNeedsDisplay];
}

在 UIView 子类 Graphics 中

@implementation GraphicsView

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

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    UIFont *helveticaBold;

    [UIFont fontWithName:@"HelveticaNeue-Bold" size:40.0f];

    NSString *myString = @"Test string function";

    [myString drawInRect:CGRectMake(20.0f,20.0f,40.0f,160.0f)
                withFont:helveticaBold];

    self.backgroundColor = [UIColor whiteColor];
}

当运行 drawRect 方法被调用但在模拟器上没有绘制。未调用 Graphics 类中的 initWithFrame 方法。 RDViewController.xib 是 Graphics 的子类。

【问题讨论】:

  • "Graphics 类中的 initWithFrame 方法没有被调用" 没问题。如果 UIView 是从 nib 实例化的,您不会期望调用此方法。而是调用initWithCoder

标签: ios core-graphics drawrect


【解决方案1】:

您从不设置字体。这样做:

- (void)drawRect:(CGRect)rect
{
    // Drawing code
    UIFont *helveticaBold = [UIFont fontWithName:@"HelveticaNeue-Bold" size:40.0f];

    NSString *myString = @"Test string function";

    [myString drawInRect:CGRectMake(20.0f,20.0f,40.0f,160.0f)
                withFont:helveticaBold];
}

并且背景颜色应该在initWithFrame:方法中设置。

【讨论】:

  • 你的意思是initWithCoderinitWithFrame 永远不会被调用。
  • 是的 initWithFrame 从未被调用,但我是否必须实现 initWithCoder 才能更改背景?
  • 很可能您可以在 IB 中设置视图的背景颜色,然后您不需要为此实现 initWithCoder
【解决方案2】:

不要在drawRect 中设置self.backgroundColor!把它放在笔尖里。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-02
    • 2011-04-05
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    相关资源
    最近更新 更多