UIView的drawRect没有被调用

时间:2011-07-19 03:44:44

标签: iphone objective-c ios ipad

我正在尝试在网格中显示水平和/或垂直线条。所以我创建了一个UIView子类GridLines,它在drawRect:中绘制线条。然后我创建其中两个(一个垂直,一个不),并将它们作为子视图添加到我的主视图(Canvas)也导出UIView。我添加到Canvas的其他自定义子视图会正确显示,删除等,但GridLines对象不会,并且永远不会调用它们的drawRect:。当我在[Canvas drawRect:](现在已禁用)中使用此线条绘制代码时,它会正确显示网格。

通过类似的问题,似乎大多数有此问题的人都在非drawRect派生类中调用UIView,但我的是UIView

我在这里错过了什么吗?

GridLines.h:

#import <UIKit/UIKit.h>
@interface GridLines : UIView
{
  BOOL mVertical;
}
- (id) initWithFrame: (CGRect) _frame vertical: (BOOL) _vertical;
@end

GridLines.m:

#import "GridLines.h"
@implementation GridLines
- (id) initWithFrame: (CGRect) _frame vertical: (BOOL) _vertical
{
  if ((self = [super initWithFrame: _frame]))
  {
    mVertical = _vertical;
  }

  return self;
}

- (void) drawRect: (CGRect) _rect
{
  NSLog(@"[GridLines drawRect]");
  CGContextRef context = UIGraphicsGetCurrentContext();
  [[UIColor clearColor] set];
  UIRectFill([self bounds]);

  if (mVertical)
  {
    for (int i = 50; i < self.frame.size.width; i += 50)
    {
      CGContextBeginPath(context);
      CGContextMoveToPoint(context, (CGFloat)i, 0.0);
      CGContextAddLineToPoint(context, (CGFloat)i, self.frame.size.height);
      [[UIColor grayColor] setStroke];
      CGContextSetLineWidth(context, 1.0);
      CGContextDrawPath(context, kCGPathFillStroke);
    }
  }
  else
  {
    for (int j = 50; j < self.frame.size.height; j += 50)
    {
      CGContextBeginPath(context);
      CGContextMoveToPoint(context, 0.0, (CGFloat)j);
      CGContextAddLineToPoint(context, self.frame.size.width, (CGFloat)j);
      [[UIColor grayColor] setStroke];
      CGContextSetLineWidth(context, 1.0);
      CGContextDrawPath(context, kCGPathFillStroke);
    }
  }
}
@end

在另一个UIView派生类中:

- (void) createGrids
{
  mHorizontalLines = [[GridLines alloc] initWithFrame: self.frame vertical: NO];
  mVerticalLines   = [[GridLines alloc] initWithFrame: self.frame vertical: YES];
  [self addSubview: mHorizontalLines];
  [self addSubview: mVerticalLines];
}

1 个答案:

答案 0 :(得分:1)

您可能遇到frame v bounds问题。

mHorizontalLines = [[GridLines alloc] initWithFrame: self.frame vertical: NO];
mVerticalLines   = [[GridLines alloc] initWithFrame: self.frame vertical: YES];

frame保留在superview的坐标空间中,如果self.frame偏移超宽,当您将这些新视图设置为该帧时,它们将被剪切为rect { {1}}。

尝试将此更改为self,其中应为origin = {0,0}