开发者

UIView's drawRect is not getting called

I am trying to display horizontal and/or vertical lines in a grid. So I created a UIView subclass GridLines that draws lines in drawRect:. I then create two of these (one vertical, one not), and add them as subviews to my primary view (Canvas) also UIView derived. The other custom subviews I add to Canvas are displayed, removed, etc. properly, but the GridLines objects are not, and their drawRect:s 开发者_开发问答never get called. When I had this line-drawing code in [Canvas drawRect:] (which is now disabled), it displayed the grid properly.

Looking through similar questions, it seems most people with this issue are calling drawRect in a non-UIView derived class, but mine is a UIView.

Am I missing something here?

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

In another UIView derived class:

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


You may have a frame v bounds problem.

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

frame is kept in superview's co-ordinate space, if self.frame is offset more that it is wide, when you set these new views to that frame, they'll be clipped to rect of self.

try changing this to self.bounds, which should have origin = {0,0}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜